.Tang

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

# cookie

# cookie
# 当你在浏览器登陆时,浏览器记录这个登录信息(服务器响应时发送请求的数据和登录信息),再次访问时 浏览器会将访问请求和缓存的登录信息都发送到服务器,
# 服务器通过这个信息判断用户是否已经登录

# @authenticated 需要
# application中配置好 login_url='login', 装饰器验证不通过则跳转到登录界面
# 写一个BaseHandler并重写get_current_user方法(该方法默认返回空)
# 该改写好 logain的登陆界面

import time
from tornado.web import authenticated   # 装饰器
from data.user_module import User
define('port',default=8000,help='run port',type=int)  # windows通过Ctrl+鼠标左键
define('version',default=0.1,help='version',type=str)


class LoginHandler(tornado.web.RequestHandler):

    def get(self):
        nextname=self.get_argument('next','')  # 从/buy跳转到登陆界面是字符串传参自动传入了next=/buy
但是直接从logain登录nextname = '',可以根据这点在logain.html中写if判断,放入两个不同的action属性的form表单
self.render('login.html', nextname=nextname, error='' # login.html用到两个参数 nextname和error ) def post(self, *args, **kwargs): nextname = self.get_argument('next', '') # 获取的上个跳转过来的路由
      # 通过获取登录的用户信息去匹配数据库 user
= self.get_argument('name', '') username = User.by_name(user) password = self.get_argument('password', '')       # 匹配后做出判断 if username and password == username[0].password: self.set_secure_cookie('ID',username[0].username) self.redirect(nextname) else: self.render('login.html', # 用户名或密码错误,再次登陆 nextname=nextname, error='用户名或密码错误' ) class BaseHandler(tornado.web.RequestHandler): # authenticated装饰器需要改写get_current_user def get_current_user(self): current_user = self.get_secure_cookie('ID') if current_user: return current_user return None class BuyHandler(BaseHandler): @authenticated # 装饰器自动验证cookie,验证通过直接访问/buy,没有则跳转到登陆界面 def get(self): self.write('欢迎你,尊贵的vip1000') application = tornado.web.Application( handlers=[ (r"/login",LoginHandler), (r"/buy",BuyHandler) ], template_path='templates', # 表明页面html的路径 static_path='static', # 表明静态文件的位置 cookie_secret='miyao', # 设置密钥 login_url='login', # 装饰器验证不通过则跳转到登录界面 debug=True # 上传代码后服务器自动重启 ) if __name__ == '__main__': tornado.options.parse_command_line() # 通过sys.arg获取命令行输入参数(python xxx.py --port=xxx) print(options.port) print(options.version) http_server = tornado.httpserver.HTTPServer(application) # 非阻塞 application.listen(options.port) tornado.ioloop.IOLoop.instance().start() # 启动io循环

 login.html

<body>
             <--!用到了两个变量 error nextname-->
{% if error %}
    用户名或密码错误
{% end %}

    <form method="post" action="/login?next={{nextname}}">
        <p>用户名 <input type="text" name="name"></p><br>
        <p>密码<input type="password" name="password"></p><br>
        <input type="submit">
    </form>
</body>

 

posted on 2018-03-13 15:36  .Tang  阅读(5821)  评论(1编辑  收藏  举报