thosphor
thosphor

Reputation: 2781

Flask session dict keys being converted to strings

I'm setting values in a Flask session on one page, and retrieving the values on the next page. In between the two, the keys in the dictionary I'm using seem to get converted from integers to strings. Is this supposed to happen?

Example:

from flask import session, redirect

@app.route('/')
def page_1():

    test = {}
    test[1] = {}
    print(test)             # outputs >>> {1: {}}

    session['store'] = {}
    session['store'][1] = {}
    return redirect('/two')

@app.route('/two')
def page_2():
    print(session)

The output of the print looks like this (and querying the dict for key 1 returns an error, while '1' works):

<SecureCookieSession {'store': {'1': {}}, 'csrf_token': 'biglongtoken...'}>

Is there any way around this? Is it supposed to happen?

Upvotes: 1

Views: 956

Answers (1)

abdusco
abdusco

Reputation: 11131

When you create a session, whatever you store inside the session is securely signed (not encrypted) and sent as a cookie to the client, and when the client reconnects to your site, it sends the cookie back, you deserialize it and access using flask.session.

https://github.com/pallets/flask/blob/1351d0a56580df36872b466eb245e7634c20dab5/src/flask/sessions.py#L378

Flask uses itsdangeous to sign the session data, which serializes your data into JSON. In JSON, keys can only be strings, non-strings are converted. When reading the cookie from the client, the keys remain strings.

https://github.com/pallets/itsdangerous/blob/8e611d7373acc874cc8bd3fc480cf3cf7b5b6a10/src/itsdangerous/serializer.py#L42

Upvotes: 3

Related Questions