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

查看:592
本文介绍了为什么通过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中的请求不到100毫秒!这对于我要做的任务更合适.时间到了.

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(...)不使用会话.
由于这个原因,每次我们调用这些方法时,每次重新配置连接以及所有其他网络连接时.
这就是为什么每次都花很多时间和以前的请求一起花费的原因.

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

Don't know why this important question doesn'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)

通过使用会话,第一次通话会花费很多时间.从第二次通话开始,在相同的域上,将花费更少的时间.

我的实验:

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天全站免登陆