Every line of 'python requests multipart form data' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.
12 def encode_multipart(data, charset='utf-8'): 13 # Ported from Werkzeug testing. 14 boundary = '---------------Boundary%s' % uuid4().hex 15 body = BytesIO() 16 17 def write(string): 18 body.write(string.encode(charset)) 19 20 if isinstance(data, dict): 21 data = data.items() 22 23 for key, values in data: 24 if not isinstance(values, (list, tuple)): 25 values = [values] 26 for value in values: 27 write('--%s\r\nContent-Disposition: form-data; name="%s"' % 28 (boundary, key)) 29 reader = getattr(value, 'read', None) 30 if reader is not None: 31 filename = getattr(value, 'filename', 32 getattr(value, 'name', None)) 33 content_type = getattr(value, 'content_type', None) 34 if content_type is None: 35 content_type = filename and \ 36 mimetypes.guess_type(filename)[0] or \ 37 'application/octet-stream' 38 if filename is not None: 39 write('; filename="%s"\r\n' % filename) 40 else: 41 write('\r\n') 42 write('Content-Type: %s\r\n\r\n' % content_type) 43 while 1: 44 chunk = reader(16384) 45 if not chunk: 46 break 47 body.write(chunk) 48 else: 49 if not isinstance(value, str): 50 value = str(value) 51 else: 52 value = value.encode(charset) 53 write('\r\n\r\n') 54 body.write(value) 55 write('\r\n') 56 write('--%s--\r\n' % boundary) 57 58 body.seek(0) 59 content_type = 'multipart/form-data; boundary=%s' % boundary 60 return body.read(), content_type
Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code