简体   繁体   English

为什么通过 Python `requests` 发送请求的时间几乎是 Postman 的 7 倍?

[英]Why does a request via Python `requests` takes almost seven times longer than in Postman?

I am currently doing a HTTP Post request to a server in Python 2.7 with requests.post() which takes around 700ms.我目前正在使用requests.post()对 Python 2.7 中的服务器执行 HTTP Post 请求,大约需要 700 毫秒。 There is also absolutely no proxy server which could cause delays but still I am bypassing any proxies because it seems to be an issue of that library.也绝对没有可能导致延迟的代理服务器,但我仍然绕过任何代理,因为这似乎是该库的问题。

Nevertheless I was curious about that time because in my opinion it takes very long for an answer with about 230 characters.尽管如此,我对那段时间很好奇,因为在我看来,大约 230 个字符的答案需要很长时间。 That is why I tried the same request in Postman.这就是为什么我在 Postman 中尝试了相同的请求。 The result was that the request in Postman took less than 100ms!结果是 Postman 中的请求耗时不到 100ms! Which is much more appropriate for the task I have to do.这更适合我必须完成的任务。 It is all about time.一切都与时间有关。

I want to know if there is any specific parameter in requests.post() which I have to set or is this function just that slow?我想知道requests.post()是否有任何我必须设置的特定参数,或者这个函数是否那么慢?

The request looks like this currently (very basic stuff):该请求目前看起来像这样(非常基本的东西):

req = requests.post(url, json={"Username": username, "Password": password, "TerminalNo": terminalno)}) 
json = req.json()

Header from the server if needed:如果需要,来自服务器的标头:

cache-control →private
content-length →228
content-type →application/json; charset=utf-8
date →Mon, 30 Jul 2018 17:58:05 GMT
server →Microsoft-IIS/7.5
x-aspnet-version →2.0.50727
x-powered-by →ASP.NET

Don't know why this important question didn't answer yet.不知道为什么这个重要的问题还没有回答。

Anyway, maybe the reason is: By default requests.get(...) or, requests.post(...) don't use sessions.无论如何,可能原因是:默认情况下requests.get(...)requests.post(...)不使用会话。
Because of this reason, every time when we call these methods, every time it reconfigures the connection and all other networking stuff.由于这个原因,每次我们调用这些方法时,每次都会重新配置连接和所有其他网络内容。
That's why every time it took much and same time as the previous requests took.这就是为什么每次都花费与先前请求花费的时间相同的原因。

To overcome this problem, we can use session.为了克服这个问题,我们可以使用 session.

import requests

url_call = "https://en.wikipedia.org/wiki/Jamal_Nazrul_Islam"
session = requests.Session()
session.get(url_call)

By using, session, it will take much time for the first call.通过使用 session,第一次调用会花费很多时间。 From the second call, on the same domain, it will take much less time.从第二次调用开始,在同一个域上,花费的时间要少得多。

My experiment:我的实验:

First call: 2154 ms第一次调用:2154 毫秒
Second call: 318 ms第二次调用:318 毫秒
Third call: 124 ms第三次调用:124 毫秒
Fourth call: 125 ms第四次调用:125 毫秒

Try using http.client尝试使用 http.client

import http.client
import json
​
conn = http.client.HTTPSConnection("example.com")
payload = {'Username': 'username', 'Password': 'password', 'TerminalNo': 'terminalno'}
body = json.dumps(payload)
headers = {
  'authorization': 'XXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX',
  'x-api-key': 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
}
​
for i in range(10):
    start = time.time()
    conn.request("GET", "/", body, headers)
    res = conn.getresponse()
    data = res.read()
    response_time = time.time() - start
    print('{} {} ms'.format(i+1, round(response_time * 1000)))

Result结果

1 906 ms
2 215 ms
3 193 ms
4 219 ms
5 203 ms
6 223 ms
7 210 ms
8 282 ms
9 204 ms
10 204 ms

This could be due to the server's response being incorrectly formatted, leading to parsing problems.这可能是由于服务器的响应格式不正确,导致解析问题。

You can check this by not reading the response you receive from the server.您可以通过不读取从服务器收到的响应来检查这一点。 If the code is still slow, this is not your problem, but if this fixed it, the problem might lie with parsing the response.如果代码仍然很慢,这不是你的问题,但如果这解决了它,问题可能在于解析响应。

  1. In case some headers are set incorrectly, this can lead to parsing errors which prevents chunked transfer ( source ).如果某些标头设置不正确,这可能会导致解析错误,从而阻止分块传输()。
  2. In other cases, setting the encoding manually might resolve parsing problems ( source ).在其他情况下,手动设置编码可能会解决解析问题 ( source )。

To fix those issues, try:要解决这些问题,请尝试:

req = requests.post(url, json={"Username": username, "Password": password, "TerminalNo": terminalno)}) 
r.raw.chunked = True # Fix issue 1
r.encoding = 'utf-8' # Fix issue 2
json = req.json()

Didn't solve your issue?没有解决你的问题?

If that did not solve your issue, I have collected some other possible solutions here .如果这不能解决您的问题,我在这里收集了一些其他可能的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么测试需要比培训更长的时间? - Why does test takes longer than training? 通过邮递员的 PUT 请求有效,但通过 python 请求无效 - PUT request via postman works, but via python requests not 为什么相同的过程在 Rust 中比在 Python 中花费更长的时间? - Why same process takes longer in Rust than in Python? 为什么python需要更长的时间来排序列表副本? - why does python takes longer time to sort a copy of list? Python-执行时间比平时更长 - Python - Execution time takes longer than usual Python 请求模块耗时过长,如果超过 x 秒,如何重新运行? - Python Request Module Taking too Long , how to rerun if takes longer than x seconds? 为什么 sqlalchemy 执行查询比使用 mysql 客户端花费更长的时间? - Why does sqlalchemy takes longer time to execute a query than using mysql client? python:结构包的大小比预期的长—为什么会发生这种情况? - python: struct pack size longer than expected — why does this happen? 通过Python Requests和Postman重新创建XMLHttpRequest的问题 - Issue with recreating XMLHttpRequest via Python Requests and Postman Python:为什么打开 XFA pdf 文件比相同大小的 txt 文件需要更长的时间? - Python: Why opening an XFA pdf file takes longer than a txt file of same size?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM