4. webpy - session

最後更新: 2021-09-27

說明

The session object is loaded with the session data before handling the request and

saves the session data after handling the request

 


store sessions in file

 

app = web.application(urls, locals())

session = web.session.Session(app, web.session.DiskStore('sessions'), initializer={'count': 0})

class count:
    def GET(self):
        session.count += 1
        return str(session.count)

* initializer argument to Session specifies the initial session.

 


store sessions in database

DBStore schema:

create table sessions (
    session_id char(128) UNIQUE NOT NULL,
    atime timestamp NOT NULL default current_timestamp,
    data text
);

Code:

app = web.application(urls, locals())

db = web.database(dbn='postgres', db='mydatabase', user='myname', pw='')

# DB, Table
store = web.session.DBStore(db, 'sessions')

session = web.session.Session(app, store, initializer={'count': 0})

 


Sessions doesn't work in debug mode

 

原因:

Since debug mode enables module reloading, the reloader loads the main module twice
2 session objects will be created.

解決

if web.config.get('_session') is None:
    session = web.session.Session(app, web.session.DiskStore('sessions'), {'count': 0})
    web.config._session = session
else:
    session = web.config._session

 


Usage

 

  • session.count
  • session.kill()

 


Setting

 

web.config.session_parameters['cookie_name'] = 'webpy_session_id'
web.config.session_parameters['cookie_domain'] = None
web.config.session_parameters['timeout'] = 86400, #24 * 60 * 60, # 24 hours   in seconds
web.config.session_parameters['ignore_expiry'] = True
web.config.session_parameters['ignore_change_ip'] = True
web.config.session_parameters['secret_key'] = 'fLjUfxqXtfNoIldA0A0J'
web.config.session_parameters['expired_message'] = 'Session expired'

 

Creative Commons license icon Creative Commons license icon