web2py insert value into session

2019-07-22 19:31发布

问题:

I am having problems with session

After a user selects smth from drop down menu I have to insert that value to session. I need that value to get to the database for auth tables in model (it crashes when I go to login/register form if I read from request.var). Where do I insert the value in session and how (view, controler).

For now I solved it using cookies but it is not the most secure.

Any suggestions=

thank you

回答1:

session is another instance of the Storage class. Whatever is stored into session for example:

session.myvariable = "hello"

can be retrieved at a later time:

a = session.myvariable

In other words, it's already there - just assign variables to it.. If you wish to use the database you have to define a session table in your DB through model. Quote from web2py manual:

For example to store sessions in the database:

session.connect(request, response, db, masterapp=None)

where db is the name of an open database connection (as returned by the DAL). It tells web2py that you want to store the sessions in the database and not on the filesystem. session.connect must come after db=DAL(...), but before any other logic that requires session, for example, setting up Auth.

web2py creates a table:

db.define_table('web2py_session',
             Field('locked', 'boolean', default=False),
             Field('client_ip'),
             Field('created_datetime', 'datetime', default=now),
             Field('modified_datetime', 'datetime'),
             Field('unique_key'),
             Field('session_data', 'text'))

and stores cPickled sessions in the session_data field.

The option masterapp=None, by default, tells web2py to try to retrieve an existing session for the application with name in request.application, in the running application.

If you want two or more applications to share sessions, set masterapp to the name of the master application.