Last active
August 29, 2015 14:05
-
-
Save dnedbaylo/d9d67bb03b3c64ae3923 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import email.utils | |
from requests.packages.urllib3.packages import six | |
def format_header_param(name, value): | |
""" | |
Helper function to format and quote a single header parameter. | |
Particularly useful for header parameters which might contain | |
non-ASCII values, like file names. This follows RFC 2231, as | |
suggested by RFC 2388 Section 4.4. | |
:param name: | |
The name of the parameter, a string expected to be ASCII only. | |
:param value: | |
The value of the parameter, provided as a unicode string. | |
""" | |
orig_value = value | |
if not any(ch in value for ch in '"\\\r\n'): | |
result = '%s="%s"' % (name, value) | |
try: | |
result.encode('ascii') | |
except UnicodeEncodeError: | |
pass | |
else: | |
return result | |
if not six.PY3: # Python 2: | |
value = value.encode('utf-8') | |
value = email.utils.encode_rfc2231(value, 'utf-8') | |
value = '%s*=%s' % (name, value) | |
if name == "name": | |
value = 'name="%s"; %s' % (orig_value, value) | |
return value | |
from requests.packages.urllib2 import fields | |
fields.format_header_param = format_header_param |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import email.utils | |
from requests.packages.urllib3.packages import six | |
def format_header_param(name, value): | |
return u'%s="%s"' % (name, value) | |
from requests.packages.urllib3 import fields | |
fields.format_header_param = format_header_param |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment