Skip to content

Instantly share code, notes, and snippets.

@fanzeyi
Created January 11, 2012 16:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save fanzeyi/1595552 to your computer and use it in GitHub Desktop.
Save fanzeyi/1595552 to your computer and use it in GitHub Desktop.
session for tornado
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
@ifduyue
Copy link

ifduyue commented Jan 12, 2012

需要加锁吧. 想想, 如果用户有开了两个tab

最好分下多级目录啊, 不然全在一个文件夹下, 文件多了会受不了的

@fanzeyi
Copy link
Author

fanzeyi commented Jan 12, 2012

@lyxint .. thanks.. 谢谢提醒 我再研究下.. 第一次写这玩意儿

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment