Created
January 11, 2012 16:46
-
-
Save fanzeyi/1595552 to your computer and use it in GitHub Desktop.
session for tornado
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import uuid | |
import marshal | |
import binascii | |
import tornado.web | |
def Session(func): | |
def warpper(self, *args, **kwargs): | |
self.require_setting("session_path", "Session") | |
_SESS_ID = self.get_secure_cookie("_SESS_ID", None) | |
if not _SESS_ID: | |
_SESS_ID = binascii.b2a_hex(uuid.uuid4().bytes) | |
self.set_secure_cookie("_SESS_ID", _SESS_ID) | |
sess_file_path = os.path.join(self.settings['session_path'], _SESS_ID + ".ses") | |
try: | |
sess_file = open(sess_file_path, "r") | |
except IOError: | |
sess_file = open(sess_file_path, "w") | |
sess_file.close() | |
self.sessions = {} | |
else: | |
os.utime(sess_file_path, None) | |
sessions = sess_file.read() | |
if sessions: | |
self.sessions = marshal.loads(sessions) | |
else: | |
self.sessions = {} | |
sess_file.close() | |
return_value = func(self, *args, **kwargs) | |
sess_file = open(sess_file_path, "w") | |
sess_file.write(marshal.dumps(self.sessions)) | |
sess_file.close() | |
return return_value | |
return warpper | |
class TestHandler(tornado.web.RequestHandler): | |
@Session | |
def get(self): | |
print self.sessions |
@lyxint .. thanks.. 谢谢提醒 我再研究下.. 第一次写这玩意儿
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
需要加锁吧. 想想, 如果用户有开了两个tab
最好分下多级目录啊, 不然全在一个文件夹下, 文件多了会受不了的