Skip to main content
 首页 » 编程设计

python之为什么 `requests`要用 `with`语句呢

2025年05月04日14飞鱼

我有一个例子:

import requests 
with requests.Session() as s: 
  s.get('http://python.su/') 

requests.get 是否使用与此示例相同的结构?

你能举出需要使用 with 语句的例子吗?

请您参考如下方法:

如 documentation 中所述,Session() 可用作上下文管理器,以便能够关闭它和所有底层使用的适配器干净时尚:

Sessions can also be used as context managers:

with requests.Session() as s: 
    s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')  

This will make sure the session is closed as soon as the with block is exited, even if unhandled exceptions occurred.

Session 可以而且应该在多个请求之间共享,持久化 cookie 和其他参数并重用相同的 TCP 连接,但是 requests.get()另一方面只是一个单一的调用,会产生一个单一的 Response 实例 - 在上下文管理器中没有意义。

请阅读以下内容以更好地理解上下文管理器: