Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `requests` use the `with` statement?

I have an example:

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

Does requests.get use the same structure as this example?

Can you give me examples where with statement is required?

like image 254
Xion Avatar asked Sep 10 '26 05:09

Xion


2 Answers

As explained in the documentation, the Session() can be used as a context manager to be able to close it and all the underlying used adapters in a clean fashion:

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.

The Session can and is supposed to be shared across multiple requests persisting cookies and other parameters and reusing the same TCP connection, but the requests.get() on the other hand is just a single call that would produce a single Response instance - there is no point in context manager for it.

Please read the following to get a better understanding of Context Managers:

  • PEP 343
  • Introduction to Context Managers in Python
  • With Statement Context Managers
like image 199
alecxe Avatar answered Sep 11 '26 18:09

alecxe


If you read the documentation for requests.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.

Making use of the with statement is a common idiom in Python to handle context management:

The with statement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers). This allows common try...except...finally usage patterns to be encapsulated for convenient reuse.

like image 40
Cory Kramer Avatar answered Sep 11 '26 19:09

Cory Kramer