首页 > 其他 > 详细

cookie、session、csrf

时间:2019-05-10 17:24:55      阅读:148      评论:0      收藏:0      [点我收藏+]

cookie的设置和获取

 1 import time
 2 from tornado.web import RequestHandler
 3 
 4 
 5 class IndexHandle(RequestHandler):
 6     def get(self):
 7         # 设置cookie
 8         self.set_cookie(username, ivy)
 9         # 设置过期时间为60s
10         self.set_cookie(username, ivy, expires=time.time() + 60)
11         # 设置过期时间为2天
12         self.set_cookie(username, ivy, expires_days=2)
13         # 当httponly为True时,网页的js代码无法获取该cookie
14         self.set_cookie(username, ivy, httponly=True)
15         # 设置cookie的过期时间为2分钟,max_age的优先级大于expires
16         self.set_cookie(username, ivy, max_age=120, expires=time.time() + 60)
17         # 设置加密的cookie,设置加密必须到app的里面去新增一个cookie_secret的参数,让这个参数等于一个字符串(盐)
18         self.set_secure_cookie(username, ivy)
19 
20 
21         # 获取cookie
22         self.get_cookie(ivy)
23         # 获取加密的cookie, 返回字节数据
24         self.get_secure_cookie(username)

 登录验证

 1 from tornado.web import RequestHandler, Application, authenticated
 2 from tornado.httpserver import HTTPServer
 3 from tornado.options import options, define
 4 from tornado.ioloop import IOLoop
 5 from util import uimethods, uimodules
 6 
 7 define(port, default=7981, type=int)
 8 
 9 
10 class BaseHandle(RequestHandler):
11     def get_current_user(self):
12         current_user = self.get_secure_cookie(username)
13         if current_user:
14             return current_user
15         return None
16 
17 
18 class IndexHandle(BaseHandle):
19     @authenticated
20     def get(self):
21         self.render(index.html)
22 
23 
24 class LoginHandle(RequestHandler):
25     def get(self):
26         self.render(login.html)
27 
28     def post(self):
29         username = self.get_argument(username)
30         password = self.get_argument(password)
31         if username == password:
32             self.set_cookie(username, password)
33             self.write(登录成功!)
34 
35 
36 application = Application(
37     handlers=[
38         (r/index, IndexHandle),
39         (r/login, LoginHandle),
40     ],
41     template_path=templates,
42     ui_methods=uimethods,
43     ui_modules=uimodules,
44     login_url=/login,
45 )
46 
47 if __name__ == __main__:
48     options.parse_command_line()
49     app = HTTPServer(application)
50     app.listen(options.port)
51     IOLoop.current().start()
  • 在登录成功之后设置cookie
  • 新建base类,重写get_current_user方法
  • get_current_user:当当前的cookie中有特定的值的时候,返回该值
  • 导入authenticated方法
  • 在需要检测时候登录的方法页面调用该函数(装饰器的方法)
  • 在app里面配置一条login_url的参数,当检测到未登录的时候(get_current_user返回None)就让页面跳转到该路由下

cookie、session、csrf

原文:https://www.cnblogs.com/ivy-blogs/p/10838415.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!