Game snake-add session support to Tornado

Source: Internet
Author: User

Warning!

Reading this article requires the ability to use Python programming and web programming experience. At least you should know what python is and what session is. Beginners should be careful when entering, some descriptions are not detailed, be careful when going astray, and welcome experts to make bricks. This articleCodeIt is used only as an example to describe the process and method of implementing session in tornado. It has not been compiled or run. Do not copy it to the project directly, I am not responsible for the consequences of this behavior. (This article is intended for commercial projects and cannot provide source code directly)

----------------------------------------------------------

Tornado does not provide default sessions, and many sensitive information cannot be stored using cookies. The secure_cookie provided by tornado only solves the problem of preventing cookie tampering and cannot prevent data from being decrypted as plain text, so I wrote a session package for Tornado to solve this problem. Well, let's take a look at how to implement the session function from the bottom.

Depending on the project's needs, I use memcached as the session's backend. Of course, you are willing to use MySQL or anything else that can store data, such as text files or MongoDB. There are many choices, therefore, we separate session persistence operations into a replaceable backend module. We can use different backend modules according to the configuration. Due to the ducktyping feature of Python, it is quite easy to implement, we only need to provide classes that contain the following three method signatures.

Class backend ():

Def getitem (self, key ):

Def setitem (self, key, value, timeout)

Def deleteitem (self, key)

 

For memcached, we need to maintain a memcached connection in the backend class. The general implementation is as follows:

From memcache import Client

Class backend ():

Def _ init _ (Self ):

Self. Conn = client (['127. 0.0.1: 100'])

Def getitem (self, key ):

Return self. Conn. Get (key)

Def setitem (self, key, value, timeout ):

Self. Conn. Set (Key, value, timeout)

Def deleteitem (self, key ):

Self. Conn. Delete (key)

Of course, in actual applications, we won't write this simple, and the connection server information is obtained from the configuration file. In this way, we have a session backend. If you want to use MySQL as the backend, you can follow this principle to rewrite a backend class.

With the persistent backend of session data, we can start to write the session class itself. First, let's review the working principle of the session. Basically, most sessions are implemented by configuring session persistence on the server through cookies. The cookie keeps the sessionid of the session created by the user, then, the session data is retrieved through sessionid to the persistent service during each access. When a request starts, the process is as follows:

When a request ends, the process is as follows:

 

We can encode the processing logic. First, we need to use an object to store session data. Generally, sessions are stored in the form of key-value, so we can use a dict as the storage object of the session, but we still need a session ID, so we inherit a dict

Class sessiondata (dict ):

Def _ Inti _ (self, id = none ):

Self. ID = ID

Def _ getitem _ (self, key ):

If self. has_key (key ):

Return self [Key]

Return none

Def _ setitem _ (self, key, value ):

Self [Key] = Value

Then we implement a decorator to restore and save the session before and after a request.

Def SESSION (request ):

Def process (handler, * ARGs ):

# Session object restoration process before request

Item = handler. application. backend. getitem (handler. get_secure_cookie ('session _ id ',''))

Data = none

If item:

Data = new sessiondata (item. ID)

Data. Update (item)

Else:

Data = new sessiondata ()

Handler. set_secure_cookie ("session_id ","")

Handler. setattr ("session", data)

Request (handler, * ARGs) # method for executing the original request

# Process of saving session after the request is complete

If data. ID:

Handler. application. backend. setitem (data. ID, data)

Else:

If Len (data. Keys ()):

Data. ID = STR (uuid1.uuid1 ())

Handler. set_secure_cookie ("session_id", Data. ID)

Handler. application. backend. setitem (data. ID, data)

 

This method is a bit long, but the logic is like this. After implementing this decreator, we only need to add @ session before the session request needs to be used to pass self. session.

 

Next, I want to solve some specific problems in the project, but the basic principles and implementation methods have ended in this article, the following work should be difficult for those who can understand this article. If they look like tianshu, most of them do not know much about Python or tornado. Please make up for the basics. I hope this article will be helpful to TX users who are practicing Python and Tornado.

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.