如何使用python的请求模块发送多个文件并自定义每个文件的标头?

时间:2015-09-17 03:52:46

标签: python python-requests

http://docs.python-requests.org/en/latest/user/quickstart/,我可以找到为单个多部分编码文件自定义标头的方法:

  

您可以明确设置文件名,content_type和标题:

files = {'file': ('report.xls', open('report.xls', 'rb'),
                  'application/vnd.ms-excel', {'Expires': '0'})}

http://docs.python-requests.org/en/latest/user/advanced/,我可以找到发送多个多部分编码文件的方法:

  

您可以在一个请求中发送多个文件...为此,请设置   文件到(form_field_name,file_info)的元组列表:

multiple_files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
                  ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]

假设我想发送以上两张图片,但我想自定义第二张图片的标题。一个合理的尝试是:

multiple_files = [('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),
                  ('images', ('bar.png', open('bar.png', 'rb'), 'image/png', {'Expires': '0'}))]

但是我收到以下错误:

In [49]: multiple_files = [('images', ('foo.png', "123", 'image/png')),
                           ('images', ('bar.png', "123", 'image/png', {'Expires': '0'}))]

In [50]: response = requests.post(
         url,
         headers={'accept': 'application/json'},
         files = multiple_files
         )
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-50-ef900c5109d7> in <module>()
      2         url,
      3         headers={'accept': 'application/json'},
----> 4         files = multiple_files
      5         )

/Library/Python/2.7/site-packages/requests-2.0.0-py2.7.egg/requests/api.pyc in post(url, data, **kwargs)
     86     """
     87
---> 88     return request('post', url, data=data, **kwargs)
     89
     90

/Library/Python/2.7/site-packages/requests-2.0.0-py2.7.egg/requests/api.pyc in request(method, url, **kwargs)
     42
     43     session = sessions.Session()
---> 44     return session.request(method=method, url=url, **kwargs)
     45
     46

/Library/Python/2.7/site-packages/requests-2.0.0-py2.7.egg/requests/sessions.pyc in request(self, method, url, params, data, headers, cookies, files, auth, timeout, allow_redirects, proxies, hooks, stream, verify, cert)
    321             hooks = hooks,
    322         )
--> 323         prep = self.prepare_request(req)
    324
    325         proxies = proxies or {}

/Library/Python/2.7/site-packages/requests-2.0.0-py2.7.egg/requests/sessions.pyc in prepare_request(self, request)
    262             auth=merge_setting(auth, self.auth),
    263             cookies=merged_cookies,
--> 264             hooks=merge_setting(request.hooks, self.hooks),
    265         )
    266         return p

/Library/Python/2.7/site-packages/requests-2.0.0-py2.7.egg/requests/models.pyc in prepare(self, method, url, headers, files, data, params, auth, cookies, hooks)
    281         self.prepare_headers(headers)
    282         self.prepare_cookies(cookies)
--> 283         self.prepare_body(data, files)
    284         self.prepare_auth(auth, url)
    285         # Note that prepare_auth must be last to enable authentication schemes

/Library/Python/2.7/site-packages/requests-2.0.0-py2.7.egg/requests/models.pyc in prepare_body(self, data, files)
    411             # Multi-part file uploads.
    412             if files:
--> 413                 (body, content_type) = self._encode_files(files, data)
    414             else:
    415                 if data:

/Library/Python/2.7/site-packages/requests-2.0.0-py2.7.egg/requests/models.pyc in _encode_files(files, data)
    124                     fn, fp = v
    125                 else:
--> 126                     fn, fp, ft = v
    127             else:
    128                 fn = guess_filename(v) or k

ValueError: too many values to unpack

我的问题是: 当存在多个文件时,我可以自定义单个文件的标题吗?

1 个答案:

答案 0 :(得分:1)

这是多部分HTTP请求的样子,所有标题都在开头,除了content-typecontent-disposition之外的多部分内容(它们描述了内容),它们仅适用于顶部级别content-typemultipart/form-data

POST /test HTTP/1.1
Host: host
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36
Accept: text/html
Accept-Language: en-us
Accept-Charset: utf-8
Keep-Alive: 300
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------3141592654
Content-Length: 111

-----------------------------3141592654
Content-Disposition: form-data; name="image"; filename="foo.png"
Content-Type: image/png
[img-data]
-----------------------------3141592654
Content-Disposition: form-data; name="image"; filename="bar.png"
Content-Type: image/png
[img-data]