I'm proxying a Flask server with another Flask server that needs to inject items into the session.
Both servers have the same secret key so the cryptographic signature will be the same. When using Flask and a session, the http response contains a Set-Cookie header with session=text
, where text is an encoded JSON string of your session object that is signed using you secret key.
Essentially, I need to be able to re-create this string, but I can't find the interface to do so.
Flask cookies 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.
The cookie used to store session data is known session cookie. However, unlike an ordinary cookie, Flask Cryptographically signs the session cookie. It means that anyone can view the contents of the cookie, but can't modify the cookie unless he has the secret key used to sign the cookie.
In Flask, cookies are set on response object. Use make_response() function to get response object from return value of a view function. After that, use the set_cookie() function of response object to store a cookie.
I ended up solving my own issue after finding [how flask does this][1] in the source. I was in a hurry at work so did not have time to better explain.
from flask import Flask, session
from flask.sessions import SecureCookieSessionInterface
app = Flask("example")
app.secret_key = "Tom Izzo 4 President"
# 1. this is what I was looking for
session_serializer = SecureCookieSessionInterface() \
.get_signing_serializer(app)
@app.route("/")
def test():
session["lst"] = ["a", "b", "c", "d"]
# 2. and this is how I needed to use it
session_cookie = session_serializer.dumps(dict(session))
The variable session_cookie
above is a valid cookie value for a session using the given secret_key. With this I am able to forward a request to another flask server that uses the secret_key.
[1]: https://github.com/pallets/flask/blob/0e79aba40d2497218736448ced708fcf4f8943b3/flask/sessions.py#L363
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