【问题标题】:Keep-alive within python-requests module在 python-requests 模块中保持活动状态
【发布时间】:2020-03-07 04:16:22
【问题描述】:

我有一个关于 python-requests 模块的问题。根据文档

感谢 urllib3,在会话中保持活动是 100% 自动的!您在会话中发出的任何请求都将自动重用相应的连接!

我的示例代码如下所示:

def make_double_get_request():
    response = requests.get(url=API_URL, headers=headers, timeout=10)
    print response.text
    response = requests.get(url=API_URL, headers=headers, timeout=10)
    print response.text

但我收到的日志表明,每次请求都会启动新的 HTTP 连接:

INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): url
DEBUG:requests.packages.urllib3.connectionpool:"GET url HTTP/1.1" 200 None
response text goes here
INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): url
DEBUG:requests.packages.urllib3.connectionpool:"GET url HTTP/1.1" 200 None
response text goes here

我做错了吗?通过使用wireshark 查看数据包,似乎它们实际上已经设置了保持活动状态。

【问题讨论】:

  • 你如何创建这些日志?
  • @kankan256 最简单的方法是打开调试日志记录,例如导入日志; logging.basicConfig(level=logging.DEBUG)

标签: python http python-requests keep-alive


【解决方案1】:

使用Session() instance

def make_double_get_request():
    session = requests.Session()
    response = session.get(url=API_URL, headers=headers, timeout=10)
    print response.text
    response = session.get(url=API_URL, headers=headers, timeout=10)
    print response.text

requests 顶级 HTTP 方法函数是一个方便的 API,它每次都会创建一个新的 Session 对象,防止重复使用连接。

来自文档:

Session 对象允许您跨请求保留某些参数。它还在会话实例发出的所有请求中保留 cookie,并将使用urllib3 的连接池。

【讨论】:

    猜你喜欢
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 2012-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多