使用 python 发送 post 请求最快的方法是什么?

Edw*_*ric 0 python post http python-requests

我尝试了普通的“请求”模块,但它真的很慢,有没有更快的方法来发送 POST 请求?

import requests 
from time import time 
t = time() 
requests.post("https://httpbin.org/post") 
print(time() - t)  # 0.884 s
Run Code Online (Sandbox Code Playgroud)

对于 GET 请求也是如此:

requests.get("https://example.com/") 
print(time() - t)  # 0.604 s
Run Code Online (Sandbox Code Playgroud)

Wil*_*lva 8

您可以使用适当命名的fast-than-requests库:

\n

pip install faster_than_requests

\n

用法:

\n
import faster_than_requests as requests\n\nrequests.post(\'https://httpbin.org/post\')\n
Run Code Online (Sandbox Code Playgroud)\n

他们提供以下比较信息:

\n
\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n
图书馆速度文件LOC依赖关系开发商WebSockets内置多线程网页抓取工具
PyWGET152.391第338章获取>17\xe2\x9d\x8c\xe2\x9d\x8c
要求15.58>202558>=7>527\xe2\x9d\x8c\xe2\x9d\x8c
请求(缓存对象)5.50>202558>=7>527\xe2\x9d\x8c\xe2\x9d\x8c
乌尔利布4.00???12000(标准库)???\xe2\x9d\x8c\xe2\x9d\x8c
网址库33.55>4052420(无 SSL),>=5(SSL)>188\xe2\x9d\x8c\xe2\x9d\x8c
pycurl0.75>155932卷曲,LibCurl>50\xe2\x9d\x8c\xe2\x9d\x8c
PyCurl(无 SSL)0.68>155932卷曲,LibCurl>50\xe2\x9d\x8c\xe2\x9d\x8c
比请求更快0.40199901\xe2\x9c\x85\xe2\x9c\x85 7,单行
\n
\n
    \n
  • 使用CLOC计算代码行数。
  • \n
  • 准备运行时包的直接依赖项。
  • \n
  • 基准测试通过此存储库上的 Dockerfile 在 Docker 上运行。
  • \n
  • 开发者是从 Git 的贡献者列表中统计的。
  • \n
  • 速度是完成 10000 个 HTTP 本地请求的 IRL 时间。
  • \n
  • 截至 2020 年的统计数据。
  • \n
  • x86_64 64 位 AMD、SSD、Arch Linux。
  • \n
\n

尽管该项目的自述文件另有说明,但我确实必须安装 Nim (以获取nimble),然后这个库才能为我工作。

\n
\n

或者,如果这不适合您,您仍然可以使用PycURL获得几乎同样好的性能。

\n

pip install pycurl

\n

不幸的是,它有一个相当复杂的 API,因为它只是 libcurl 的一个薄包装。这是一个基本示例:

\n
from io import BytesIO\n\nimport pycurl\n\n\nbuffer = BytesIO()\n\nc = pycurl.Curl()\nc.setopt(c.URL, \'http://pycurl.io/\')\nc.setopt(c.WRITEDATA, buffer)\nc.perform()\nc.getinfo(pycurl.RESPONSE_CODE) # ensure this equals 200, or otherwise handle it\nc.close()\n\nbuffer.seek(0)\nbuffer.read() # the response text as bytes\n
Run Code Online (Sandbox Code Playgroud)\n

有关更复杂的示例以及有关如何使用 API 的更多信息,请参阅文档

\n
\n

接下来按照性能降低的顺序,如果您正在寻找更好的 API,您可能会对 urllib3 感兴趣:

\n

pip install urllib3

\n

不要与内置库 urllib 混淆(见下文)。有趣的是,urllib3 是 Requests 的后端。

\n

用法:

\n
import urllib3\n\n\nhttp = urllib3.PoolManager()\nresponse = http.request(\'POST\', \'http://httpbin.org/post\')\nresponse.status # ensure this equals 200, or otherwise handle it\nresponse.data # the response text as bytes\n
Run Code Online (Sandbox Code Playgroud)\n
\n

为了完整起见,我还应该提到这urllib.requests是一个选项。

\n

用法:

\n
import urllib.request\n\n\nrequest = urllib.request.Request(\'https://httpbin.org/post\', method=\'POST\')\n\nwith urllib.request.urlopen(request) as response:\n    response.status # ensure this equals 200, or otherwise handle it\n    response.read() # the response text as bytes\n
Run Code Online (Sandbox Code Playgroud)\n