Python implements session

Source: Internet
Author: User

Python implements session

First, save the session generated by the browser to the master program on the disk.

#-*-Coding: UTF-8 -*-
'''
@ Author: cuiruiqiang
@ Date: 2014-12-3
@ Filename: CountSession. py count session's number
'''
Import web


Web. config. debug = False
Urls = (
'/', 'Index ',
'/Count', 'Count ',
'/Reset', 'reset'
)
App = web. application (urls, locals ())
# Session is be stored on disk. Save the session on the local disk.
Session = web. session. Session (app, web. session. DiskStore ('session '),
Initializer = {'Count': 0 })


Class count:
Def GET (self ):
Session. count + = 1
Return str (session. count)
Class reset:
Def GET (self ):
Session. kill ()
Return ""
If _ name _ = "_ main __":
App. run ()


Second, save the session information of the browser in mysql.

The table structure is as follows:

Create table sessions (

Session_id char (128) unique not null,
Atime timestamp not null default current_timestamp,
Data text)

#-*-Coding: UTF-8 -*-
'''
@ Author: cuiruiqiang
@ Date: 2014-3 3
@ Filename: server. py
'''
Import web
Web. config. debug = False
Urls = (
'/', 'Index ',
'/Count', 'Count ',
'/Reset', 'reset'
)
App = web. application (urls, locals ())
# Session is be stored database stores session information in the database.
Db = web. database (dbn = 'mysql', db = 'py', user = 'root', pw = '123 ')
Store = web. session. DBStore (db, 'session ')
Session = web. session. Session (app, store, initializer = {'Count': 0 })

Render = web. template. render ('template/', globals = {'context': session })


Class index:
Def GET (self ):
Return render. index ()
Class count:
Def GET (self ):
Session. count + = 1
Return str (session. count)
Class reset:
Def GET (self ):
Session. kill ()
Return ""
If _ name _ = "_ main __":
App. run ()

The index.html file is as follows:




Test sessions




You are logged in$ Context. count



>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.