How to use the library requests
(in python) after a request
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests bot = requests.session() bot.get('http://google.com')
to keep all the cookies in a file and then restore the cookies from a file.
Create cookie In Flask, set the cookie on the response object. Use the make_response() function to get the response object from the return value of the view function. After that, the cookie is stored using the set_cookie() function of the response object. It is easy to read back cookies.
To send a request with a Cookie, you need to add the "Cookie: name=value" header to your request. To send multiple cookies in a single Cookie header, separate them with semicolons or add multiple "Cookie: name=value" request headers.
There is no immediate way to do so, but it's not hard to do.
You can get a CookieJar
object from the session with session.cookies
, and use pickle
to store it to a file.
A full example:
import requests, pickle session = requests.session() # Make some calls with open('somefile', 'wb') as f: pickle.dump(session.cookies, f)
Loading is then:
session = requests.session() # or an existing session with open('somefile', 'rb') as f: session.cookies.update(pickle.load(f))
The requests
library uses the requests.cookies.RequestsCookieJar()
subclass, which explicitly supports pickling and a dict-like API. The RequestsCookieJar.update()
method can be used to update an existing session cookie jar with the cookies loaded from the pickle file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With