我是Python和MongoDB环境的新手。我正在使用Tornado + MongoDB在Python中实现一个小应用程序。我想在mongoDB中存储会话。
在server.py
import os
import tornado.web
import tornado.ioloop
import settings
application = tornado.web.Application(
settings.urls,
my_template_path,
my_static_path
)
if __nam__ == '__main__':
application.listen(8000)
tornado.ioloop.IOLoop.instance().start()
在settings.py
import handler as H
urls = [
(r"/", H.ShowHome),
(r"/login", H.ShowLogin),
(r"/dashboard", H.ShowDashboard)
]
在handler.py
import os
# import session or some library ????
class ShowHome(tornado.web.RequestHandler):
SESSION = False
def initialize(self):
#
# check session related things here
#
# self.SESSION = True or False based on session cookie
def get(self):
if not self.SESSION:
self.redirect('/login')
else:
self.render('index.html')
class ShowLogin(tornado.web.RequestHandler):
SESSION = False
def initialize(self):
#
# check session related things here
#
# self.SESSION = True or False based on session cookie
def get(self):
if self.SESSION:
self.redirect('/dashboard')
else:
self.render('login.html')
class ShowDashboard(tornado.web.RequestHandler):
SESSION = False
def initialize(self):
#
# check session related things here
#
# self.session = True or False based on session cookie
def get(self):
if not SESSION:
self.redirect('/login')
else:
self.render('dashboard.html')
在处理程序中我想检查会话,我该怎么做?
答案 0 :(得分:2)
你的意思是这样吗?
class Base(tornado.web.RequestHandler):
def get_unique_id(self):
return self.get_secure_cookie('unique_id')
def set_unique_id(self, some_value):
return self.set_secure_cookie('unique_id', some_value)
class ShowLogin(Base):
def get(self):
if get_unique_id():
# Get stuff from Mongo using unique_id
# mongo calls
self.redirect('/dashboard')
else:
self.render('login.html')
class LoginLogin(Base):
def post(self):
self.set_unique_id(some_id)
你可能不想这样做 - 如果某人登录或退出authenticated decorator
,请让Tornado处理除非您持有大量数据或非常敏感的数据,否则将会话数据放入cookie中是正常的(并且更容易)