0

我是 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')

在我想检查会话的处理程序中,我该怎么做?

4

1 回答 1

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)

不过,您可能不想这样做 - 如果有人使用经过身份验证的装饰器登录或注销,请让 Tornado 处理

除非您持有大量数据或非常敏感的数据,否则将会话数据放入 cookie 是正常的(也更容易)

于 2013-10-17T16:12:16.103 回答