Kanin Peanviriyakulkit Kanin Peanviriyakulkit - 1 year ago 165
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:
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

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 ?


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

but it error like this:

Python Requests trying to post data to Laravel


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

Thank you all.

Answer Source

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')


fh = open('file.txt', 'w')
fh.write('Hello, world')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download