tornado 中没有session功能,需要我们自己实现。

 

目录:

 

settings:

settings = {
    'template_path': 'templates',
    'static': 'static'
}

home:

#!/usr/bin/env python
# Version = 3.5.2
# __auth__ = '无名小妖'
import tornado.web
import hashlib
import time

container = {}


def md5():
    m = hashlib.md5()
    m.update(bytes(str(time.time()), encoding='utf8'))
    return m.hexdigest()


class Session:

    def __init__(self, handler):
        random_str = handler.get_cookie('__session_id__')
        if random_str:
            if random_str in container:
                self.r_str = random_str
            else:
                random_str = md5()
                container[random_str] = {}
                self.r_str = random_str
        else:
            random_str = md5()
            container[random_str] = {}
            self.r_str = random_str
        handler.set_cookie('__session_id__', random_str, expires=time.time()+200)

    def set_session(self, key, value):
        ret = container[self.r_str][key] = value
        return ret

    def get_session(self, key):
        ret = container[self.r_str].get(key, None)
        return ret


class BaseHandler(tornado.web.RequestHandler):
    def initialize(self):
        self.session_info = Session(self)


class MainHandler(BaseHandler):
    def get(self):
        # self.write("Hello, world")
        self.render('index.html')

    def post(self, *args, **kwargs):
        user = self.get_argument('user')
        pwd = self.get_argument('pwd')
        if user == 'xiao' and pwd == '123':
            self.session_info.set_session('is_login', True)
            self.session_info.set_session('user', user)
            self.redirect('/main')
        else:
            self.redirect('/index')


class IndexHandler(BaseHandler):
    def get(self):
        current_user = self.session_info.get_session('user')
        if current_user:
            self.write(current_user)
        else:
            self.write('未登录')

  注:自己写个session类,再重写initialize方法。

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/index" method="post">
        <input type="text" name="user">
        <input type="text" name="pwd">
        <input type="submit" value="提交">
    </form>
</body>
</html>

app:

from tornado import ioloop
import tornado.web
from controler.home import MainHandler, IndexHandler
from commons.settings import settings


application = tornado.web.Application([
    (r"/index", MainHandler),  # url--对应类,django对应的是函数
    (r"/main", IndexHandler),  # url--对应类,django对应的是函数
],
    **settings  # 加载配置
)


if __name__ == "__main__":
    application.listen(8888)
    ioloop.IOLoop.instance().start()

  

效果:

未登录时,访问main:

登录:

登陆后:

证明已登录。