Skip to content

Commit

Permalink
Encode Multipart Post data at Request creation
Browse files Browse the repository at this point in the history
This fixes psf#298 (File upload not working with
HTTP digest authentication)
  • Loading branch information
catwell committed Apr 12, 2012
1 parent c3e6c41 commit f3ad56f
Showing 1 changed file with 27 additions and 22 deletions.
49 changes: 27 additions & 22 deletions requests/models.py
Expand Up @@ -80,7 +80,7 @@ def __init__(self,
self.headers = dict(headers or [])

#: Dictionary of files to multipart upload (``{filename: content}``).
self.files = files
self.files = None

#: HTTP Method to use.
self.method = method
Expand Down Expand Up @@ -114,6 +114,7 @@ def __init__(self,

self.data, self._enc_data = self._encode_params(data)
self.params, self._enc_params = self._encode_params(params)
self.files, self._enc_files = self._encode_files(files)

#: :class:`Response <Response>` instance, containing
#: content and metadata of HTTP Response, once :attr:`sent <send>`.
Expand Down Expand Up @@ -329,6 +330,29 @@ def _encode_params(data):
else:
return data, data

def _encode_files(self,files):

if (not files) or isinstance(self.data, str):
return None, None

try:
fields = self.data.copy()
except AttributeError:
fields = dict(self.data)

for (k, v) in list(files.items()):
# support for explicit filename
if isinstance(v, (tuple, list)):
fn, fp = v
else:
fn = guess_filename(v) or k
fp = v
fields.update({k: (fn, fp.read())})

(body, content_type) = encode_multipart_formdata(fields)

return files, (body, content_type)

@property
def full_url(self):
"""Build the actual URL to use."""
Expand Down Expand Up @@ -447,26 +471,7 @@ def send(self, anyway=False, prefetch=False):

# Multi-part file uploads.
if self.files:
if not isinstance(self.data, str):

try:
fields = self.data.copy()
except AttributeError:
fields = dict(self.data)

for (k, v) in list(self.files.items()):
# support for explicit filename
if isinstance(v, (tuple, list)):
fn, fp = v
else:
fn = guess_filename(v) or k
fp = v
fields.update({k: (fn, fp.read())})

(body, content_type) = encode_multipart_formdata(fields)
else:
pass
# TODO: Conflict?
(body, content_type) = self._enc_files
else:
if self.data:

Expand Down Expand Up @@ -763,7 +768,7 @@ def content(self):
except AttributeError:
self._content = None

self._content_consumed = True
self._content_consumed = True
return self._content

def _detected_encoding(self):
Expand Down

0 comments on commit f3ad56f

Please sign in to comment.