在单个连接中进行多个请求?

3 投票
2 回答
8497 浏览
提问于 2025-04-15 17:02

有没有办法在使用python的httplib时,不断开连接的情况下发送多个请求呢?比如,我能不能把一个大文件分成几部分上传到服务器,但还是用同一个连接。

我查了很多资料,但都没有找到特别清楚和明确的答案。

如果有相关的例子或者链接,那就太好了。谢谢!

2 个回答

2

你需要确保在你的响应上调用 .read() 这个函数。否则你会遇到类似下面的错误:

Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    conn.request("GET", "/2.html")
  File "C:\Python27\lib\httplib.py", line 955, in request
    self._send_request(method, url, body, headers)
  File "C:\Python27\lib\httplib.py", line 983, in _send_request
    self.putrequest(method, url, **skips)
  File "C:\Python27\lib\httplib.py", line 853, in putrequest
    raise CannotSendRequest()
CannotSendRequest

这个错误会出现,如果返回的数据没有被读取(即使没有数据返回,或者收到了HTTP错误,比如404错误)。

13

是的,连接会一直保持打开状态,直到你用 close() 方法把它关闭。

下面这个例子,来自于 httplib 的文档,展示了如何通过一个连接来进行多次请求:

>>> import httplib
>>> conn = httplib.HTTPConnection("www.python.org")
>>> conn.request("GET", "/index.html")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK
>>> data1 = r1.read()
>>> conn.request("GET", "/parrot.spam")
>>> r2 = conn.getresponse()
>>> print r2.status, r2.reason
404 Not Found
>>> data2 = r2.read()
>>> conn.close()

撰写回答