2

我们有一些自定义模块,我们在其中重新定义了open, seek, read,tell函数以根据参数仅读取文件的一部分。

但是,这个逻辑覆盖了默认值tell,pythonrequests正在尝试计算涉及 using的内容长度tell(),然后重定向到我们的自定义tell函数,并且逻辑在某处有问题并返回错误的值。我尝试了一些更改,它会引发错误。

从请求的 models.py 中找到以下内容:

 def prepare_content_length(self, body):
        if hasattr(body, 'seek') and hasattr(body, 'tell'):
            body.seek(0, 2)
            self.headers['Content-Length'] = builtin_str(body.tell())
            body.seek(0, 0)
        elif body is not None:
            l = super_len(body)
            if l:
                self.headers['Content-Length'] = builtin_str(l)
        elif (self.method not in ('GET', 'HEAD')) and (self.headers.get('Content-Length') is None):
            self.headers['Content-Length'] = '0'

目前,我无法弄清楚错误在哪里,并强调要进行更多调查并修复它。除了 python 请求的内容长度计算之外,其他一切都有效。

因此,我创建了自己的定义来查找内容长度。我已经在请求标头中包含了该值。但是,请求仍在准备内容长度并抛出错误。

如何限制不准备内容长度并使用指定的内容长度?

4

1 回答 1

7

Requests 允许您在发送之前修改请求。请参阅准备好的请求

例如:

from requests import Request, Session

s = Session()

req = Request('POST', url, data=data, headers=headers)
prepped = req.prepare()

# do something with prepped.headers
prepped.headers['Content-Length'] = your_custom_content_length_calculation()

resp = s.send(prepped, ...)

如果您的会话有自己的配置(如 cookie 持久性或连接池),那么您应该s.prepare_request(req)使用req.prepare().

于 2016-04-06T18:01:24.567 回答