Reputation: 25997
I have an application where I make a request
like this:
headers = {'Content-Type': 'application/json;charset=ISO-8859-1'}
d = {'db_name': 'a_database', 'username': 'me', 'password': 'apw'}
db_url = "http://123.45.67.89:1234/something/rest/connections"
r = requests.post(db_url, data=json.dumps(d), headers=headers)
This will then create a cookie:
r.cookies
<RequestsCookieJar[Cookie(version=0, name='removed', value='removed', port=None, port_specified=False, domain='123.45.67.89', domain_specified=False, domain_initial_dot=False, path='/something', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={}, rfc2109=False), Cookie(version=0, name='connectname', value='alsoremoved', port=None, port_specified=False, domain='123.45.67.89', domain_specified=False, domain_initial_dot=False, path='/something/rest', path_specified=False, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest={'HttpOnly': None}, rfc2109=False)]>
I can then use r.cookies
to make additional requests
where I then specify cookies=r.cookies
.
In my flask application, I would like to use the cookie
in several functions, so I thought I would store it in session
:
from flask import Flask, render_template, request, jsonify, session
session['cookies'] = r.cookies
so that I can then later use
r2 = requests.post(someurl, data=json.dumps(anotherd), headers=headers, cookies=session['cookies'])
However, that results in
Object of type 'RequestsCookieJar' is not JSON serializable
How would I store r.cookies
so that it is available in all functions in my application but can vary between users?
Upvotes: 2
Views: 3727
Reputation: 1121168
You can't store the RequestsCookieJar
, no, but if all you want are the names and values of the cookies, you can trivially convert the jar to a dictionary:
session['cookies'] = r.cookies.get_dict()
The RequestsCookieJar.get_dict()
method also supports filtering by domain and path.
For future requests, the cookies
parameter of requests.<METHOD>(...)
calls accepts such a dictionary directly.
Upvotes: 4