Clemens
Clemens

Reputation: 33

web2py: Dynamically defined session variables

Hello web2py community!

I'm currently developing a control mechanism between components all operating on common data cluster named model which is identified by model_id. The communication between the components is realized via session variables.

But since the user should have the option to operate on several models in parallel, I need to differentiate the session variables used for each model.

For this purpose I want to complement the different session variables by the model_id as unique identifier.

To read such a session variable is the easy part, e.g.

current_action = eval('session.manage_action_%s' % model_id)

But writing a new value to that session variable doesn't work. My solution until now is as follows:

vars()['session.manage_action_%s' % model_id] = new_action

This only produces a local variable session.manage_action_5 (or whatever value of model_id). But it's not a real, reusable and readable session variable.

Thus my question is:

How can I generate a dynamically defined session variable depending on a variable value read on runtime?

Thanks for any support in advance, since it would be great to have a solution for that ...

Best regards, Clemens

Upvotes: 0

Views: 190

Answers (1)

Anthony
Anthony

Reputation: 25536

The session object is a dictionary-like object, so you can use dictionary syntax for dynamically generated keys:

session['manage_action_%s' % model_id] = new_action
current_action = session['manage_action_%s' % model_id]

or:

session.update(**{'manage_action_%s' % model_id: new_action})
current_action = session.get('manage_action_%s' % model_id)

Upvotes: 1

Related Questions