Python Requests and persistent sessions
You can easily create a persistent session using:
s = requests.Session()
After that, continue with your requests as you would:
s.post('https://localhost/login.py', login_data)
# logged in! cookies saved for future requests.
r2 = s.get('https://localhost/profile_data.json', ...)
# cookies sent automatically!
# do whatever, s will keep your cookies intact :)
For more about Session
s: https://requests.readthedocs.io/en/latest/user/advanced/#session-objects
How can you persist a single authenticated requests session in python?
I'd wire up a property like this:
class RestClient:
_session = None
@property
def session(self):
if self._session:
return self._session
auth = requests.auth.HTTPBasicAuth(USERNAME, PASSWORD)
response = requests.post(
f"https://{ settings.HOST }/rest/session", auth=auth
)
session = requests.Session()
session_id = response.json().get("value")
session.headers.update({"api-session-id": session_id})
self._session = session
return session
Now you can simply do client.session
and it will be set up on the first access and reused thereafter.
EDIT: To persist this between RestClient
instances, change references to self._session
to RestClient._session
.
Store python requests session in persistent storage
If you use the dill
package, you should be able to pickle the session where pickle
itself fails.
>>> import dill as pickle
>>> pickled = pickle.dumps(session)
>>> restored = pickle.loads(pickled)
Get dill
here: https://github.com/uqfoundation/dill
Actually, dill
also makes it easy to store your python session across restarts, so you
could pickle
your entire python session like this:
>>> pickle.dump_session('session.pkl')
Then restart python, and pick up where you left off.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill as pickle
>>> pickle.load_session('session.pkl')
>>> restored
<requests.sessions.Session object at 0x10c012690>
Related Topics
Sort List of Lists Ascending and Then Descending
Python: Problem with Raw_Input Reading a Number
In Practice, What Are the Main Uses for the "Yield From" Syntax in Python 3.3
Replace Values in List Using Python
Importing Variables from Another File
Parsing Boolean Values with Argparse
How to Get Different Colored Lines for Different Plots in a Single Figure
How to Get a List of All the Duplicate Items Using Pandas in Python
How to Add Custom Methods/Attributes to Built-In Python Types
Scraping: Ssl: Certificate_Verify_Failed Error for Http://En.Wikipedia.Org
Case Insensitive Regular Expression Without Re.Compile
How to Execute Raw SQL in Flask-Sqlalchemy App
Windows Scipy Install: No Lapack/Blas Resources Found
What Do Square Brackets, "[]", Mean in Function/Class Documentation