单个连接中的多个请求?

发布于 2024-08-15 01:55:30 字数 141 浏览 6 评论 0原文

是否可以使用 python httplib 在不中断连接的情况下发出多个请求? 例如,我可以将一个大文件部分上传到服务器,但在单个套接字连接中吗?

我寻找答案。但似乎没有什么事情是那么清晰明确。

任何示例/相关链接都会有所帮助。 谢谢。

Is it possible to put multiple requests without breaking the connection using python httplib?.
Like, can I upload a big file to the server in parts but in a single socket connection.

I looked for answers. But nothing seemed so clear and definite.

Any examples/related links will be helpfull.
Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

雪若未夕 2024-08-22 01:55:30

是的,连接将保持打开状态,直到您使用 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()

Yes, the connection stays open until you close it using the close() method.

The following example, taken from the httplib documentation, shows how to perform multiple requests using a single connection:

>>> 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()
泪痕残 2024-08-22 01:55:30

您需要确保在响应中调用 .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]),则会引发此异常。

You need to be sure to call the .read() function on your response. Otherwise you'll get an error like:

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

This exception is raised if the return data has not been read (even if no data is returned, or an HTTP error was recieved [a 404 for example]).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文