Kanin Peanviriyakulkit Kanin Peanviriyakulkit - 1 month ago 12
Python Question

How to use Python Requests session to a longtime?

I don't know how to ask this question but I will explain it.

I use Requests to login to website like this

URL = 'http://test.dev/api/login'
with requests.session() as s:
s.get(URL)
login_data = {'username': 'test', 'password': 'testtest'}
ra=s.post(URL, data=login_data)
# Now I got session and cookie I can go to another pages like
r=s.get('http://test.dev/api/user/1')


When login success the server sent the session and cookie back.

But if I go out the the loop "with" I must login again?

Question is how can I go another page with out the "with" loop ?

EDIT1:


EDIT: I try to use at s=requests.Session() firstime

but it error like this:

Python Requests trying to post data to Laravel

EDIT2:


I try to use s = requests.session() again and it work I don't know why = =

Thank you all.

Answer

To expand on Daniel's answer the with block is a context manager. It will open a new context for you, in your case your call to requests.session(). Once the block is completed the the context it will be closed.

In your example once the line r=s.get(...) is completed there is no more code for the context so it is closed. For example these two blocks achieve the same result:

with open('file.txt', 'w') as fh:
    fh.write('Hello, world')

and

fh = open('file.txt', 'w')
fh.write('Hello, world')
fh.close()