python.requests中关闭文件的I / O操作

时间:2014-08-17 10:43:18

标签: python

我有一个非常简单的代码:

from rauth import OAuth1Session, OAuth1Service
import requests, urllib

#preparing...
#...

#request
session.request(request_type, url, header_auth, headers = headers, files = {'file' : open('./my_file.pdf', 'rb')}, **req_kwargs)

错误为ValueError: I/O operation on closed file

这是什么?

File "/Library/Python/2.7/site-packages/rauth/session.py", line 210, in request
    return super(OAuth1Session, self).request(method, url, **req_kwargs)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 422, in request
    prep = self.prepare_request(req)
  File "/Library/Python/2.7/site-packages/requests/sessions.py", line 360, in prepare_request
    hooks=merge_hooks(request.hooks, self.hooks),
  File "/Library/Python/2.7/site-packages/requests/models.py", line 297, in prepare
    self.prepare_body(data, files)
  File "/Library/Python/2.7/site-packages/requests/models.py", line 432, in prepare_body
    (body, content_type) = self._encode_files(files, data)
  File "/Library/Python/2.7/site-packages/requests/models.py", line 147, in _encode_files
    rf = RequestField(name=k, data=fp.read(),
ValueError: I/O operation on closed file`

1 个答案:

答案 0 :(得分:0)

OAuth1Session对象将首先建立一个令牌(它可能需要获得一个新令牌);这可能导致在发布实际请求之前读取和发布文件。

您可能需要首先执行不同的请求而不上传文件来建立令牌,然后上传文件。

或者首先将整个文件读入内存而不是传递文件对象:

session.request(request_type, url, header_auth, headers=headers,
                files={'file': open('./my_file.pdf', 'rb').read()},
                **req_kwargs)