为什么通过 Python `requests` 发出请求的时间几乎是 Postman 的七倍? [英] Why does a request via Python `requests` takes almost seven times longer than in Postman?

查看:29
本文介绍了为什么通过 Python `requests` 发出请求的时间几乎是 Postman 的七倍?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 requests.post() 对 Python 2.7 中的服务器执行 HTTP Post 请求,大约需要 700 毫秒.也绝对没有可能导致延迟的代理服务器,但我仍然绕过任何代理,因为这似乎是该库的问题.

I am currently doing a HTTP Post request to a server in Python 2.7 with requests.post() which takes around 700ms. 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.

尽管如此,我还是对那段时间很好奇,因为在我看来,大约 230 个字符的答案需要很长时间.这就是为什么我在 Postman 中尝试了相同的请求.结果是Postman中的请求耗时不到100ms!这更适合我必须完成的任务.时间到了.

Nevertheless I was curious about that time because in my opinion it takes very long for an answer with about 230 characters. That is why I tried the same request in Postman. The result was that the request in Postman took less than 100ms! Which is much more appropriate for the task I have to do. It is all about time.

我想知道 requests.post() 中是否有任何我必须设置的特定参数,或者这个函数有那么慢吗?

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?

请求目前看起来像这样(非常基本的东西):

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

推荐答案

不知道为什么这个重要的问题还没有回答.

无论如何,原因可能是:默认情况下 requests.get(...) 或者 requests.post(...) 不使用会话.
由于这个原因,每次我们调用这些方法时,每次都会重新配置连接和所有其他网络内容.
这就是为什么每次都花费与先前请求花费的时间相同的原因.

为了克服这个问题,我们可以使用 session.

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.
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.

import requests

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

通过使用 session,第一次调用会花费很多时间.从第二次调用开始,在同一个域上,花费的时间会少得多.

我的实验:

By using, session, it will take much time for the first call. From the second call, on the same domain, it will take much less time.

My experiment:

第一次调用:2154 毫秒
第二次调用:318 毫秒
第三次调用:124 毫秒
第四次调用:125 毫秒

First call: 2154 ms
Second call: 318 ms
Third call: 124 ms
Fourth call: 125 ms

这篇关于为什么通过 Python `requests` 发出请求的时间几乎是 Postman 的七倍?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆