pull python-ox changes

This commit is contained in:
j 2014-10-04 21:08:57 +02:00
commit 7040fdd564
13 changed files with 75 additions and 57 deletions

View file

@ -8,6 +8,8 @@ import mimetypes
import random
import sys
from six import PY2
__all__ = ['MultiPartForm']
@ -36,19 +38,19 @@ class MultiPartForm(object):
def add_field(self, name, value):
"""Add a simple field to the form data."""
if isinstance(name, unicode):
name = name.encode('utf-8')
if isinstance(value, unicode):
value = value.encode('utf-8')
if isinstance(name, bytes):
name = name.decode('utf-8')
if isinstance(value, bytes):
value = value.decode('utf-8')
self.form_fields.append((name, value))
return
def add_file(self, fieldname, filename, fileHandle, mimetype=None):
"""Add a file to be uploaded."""
if isinstance(fieldname, unicode):
fieldname = fieldname.encode('utf-8')
if isinstance(filename, unicode):
filename = filename.encode('utf-8')
if isinstance(fieldname, bytes):
fieldname = fieldname.decode('utf-8')
if isinstance(filename, bytes):
filename = filename.decode('utf-8')
if hasattr(fileHandle, 'read'):
body = fileHandle.read()
@ -58,8 +60,14 @@ class MultiPartForm(object):
mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
self.files.append((fieldname, filename, mimetype, body))
return
def __str__(self):
body = self.body()
if not PY2:
body = body.decode('utf-8')
return body
def body(self):
"""Return a string representing the form data, including attached files."""
# Build a list of lists, each containing "lines" of the
# request. Each part is separated by a boundary string.
@ -95,5 +103,6 @@ class MultiPartForm(object):
flattened = list(itertools.chain(*parts))
flattened.append('--' + self.boundary + '--')
flattened.append('')
return '\r\n'.join(flattened)
flattened = [part if isinstance(part, bytes) else part.encode('utf-8') for part in flattened]
return b'\r\n'.join(flattened)