ramesh
ramesh

Reputation: 1207

Pop value from dictionary stored in Flask session

Here is my session variable,

session['data'] = json.loads(request.data.decode())
print(session.pop('data', None))

Print looks like this:

{u'mark': u'all', u'chr': u'1A', u'distmin': 5, u'distmax': 10}

My question is, how to subset this dict,

print(session.pop('data["mark"]', None))

This is not working, this returns None.

Upvotes: 0

Views: 1119

Answers (1)

dirn
dirn

Reputation: 20709

That isn't how Python's mappings work. data["mark"] is a valid key. To access nested mappings, you need to specify the keys separately.

session['data']['mark'] = 'spam'

The key used for pop should match that for __getitem__. Just as you don't use session['data["mark"]'] to access the dictionary associated with the data key, you wouldn't remove keys the same way. The syntax you're looking for is

session['data'].pop('mark', None)

Mark the session as modified after changing a nested object like this. The session can only do this automatically for direct changes.

session.modified = True

Upvotes: 3

Related Questions