cookie、session、csrf
2024-09-04 21:22:42
cookie的设置和获取
import time
from tornado.web import RequestHandler class IndexHandle(RequestHandler):
def get(self):
# 设置cookie
self.set_cookie('username', 'ivy')
# 设置过期时间为60s
self.set_cookie('username', 'ivy', expires=time.time() + 60)
# 设置过期时间为2天
self.set_cookie('username', 'ivy', expires_days=2)
# 当httponly为True时,网页的js代码无法获取该cookie
self.set_cookie('username', 'ivy', httponly=True)
# 设置cookie的过期时间为2分钟,max_age的优先级大于expires
self.set_cookie('username', 'ivy', max_age=120, expires=time.time() + 60)
# 设置加密的cookie,设置加密必须到app的里面去新增一个cookie_secret的参数,让这个参数等于一个字符串(盐)
self.set_secure_cookie('username', 'ivy') # 获取cookie
self.get_cookie('ivy')
# 获取加密的cookie, 返回字节数据
self.get_secure_cookie('username')
登录验证
from tornado.web import RequestHandler, Application, authenticated
from tornado.httpserver import HTTPServer
from tornado.options import options, define
from tornado.ioloop import IOLoop
from util import uimethods, uimodules define('port', default=7981, type=int) class BaseHandle(RequestHandler):
def get_current_user(self):
current_user = self.get_secure_cookie('username')
if current_user:
return current_user
return None class IndexHandle(BaseHandle):
@authenticated
def get(self):
self.render('index.html') class LoginHandle(RequestHandler):
def get(self):
self.render('login.html') def post(self):
username = self.get_argument('username')
password = self.get_argument('password')
if username == password:
self.set_cookie(username, password)
self.write('登录成功!') application = Application(
handlers=[
(r'/index', IndexHandle),
(r'/login', LoginHandle),
],
template_path='templates',
ui_methods=uimethods,
ui_modules=uimodules,
login_url='/login',
) if __name__ == '__main__':
options.parse_command_line()
app = HTTPServer(application)
app.listen(options.port)
IOLoop.current().start()
- 在登录成功之后设置cookie
- 新建base类,重写get_current_user方法
- get_current_user:当当前的cookie中有特定的值的时候,返回该值
- 导入authenticated方法
- 在需要检测时候登录的方法页面调用该函数(装饰器的方法)
- 在app里面配置一条login_url的参数,当检测到未登录的时候(get_current_user返回None)就让页面跳转到该路由下
验证登录后跳转回原页面
from tornado.web import RequestHandler, authenticated class BaseHandle(RequestHandler):
def get_current_user(self):
current_user = self.get_cookie('login')
if current_user:
return current_user class IndexHandle(BaseHandle):
@authenticated
def get(self):
self.write('index 页面') class LoginHandle(BaseHandle):
def get(self):
next_url = self.get_argument('next', '')
self.render('login.html', next_url=next_url) def post(self):
username = self.get_argument('username', '')
password = self.get_argument('password', '')
next_url = self.get_argument('next', '')
if username == password and next_url:
self.set_secure_cookie('login', 'true')
self.redirect(next_url)
elif username == password:
self.set_secure_cookie('login', 'true')
self.write('登录成功!')
from tornado.web import Application
from tornado.options import options
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
import handles settings = {
'template_path': 'templates',
'static_path': 'static',
'cookie_secret': 'summer',
'login_url': '/login' } urlpatterns = [
(r'/login', handles.LoginHandle),
(r'/index', handles.IndexHandle),
] app = Application(handlers=urlpatterns, **settings) if __name__ == '__main__':
options.parse_command_line()
http = HTTPServer(app)
http.listen(80)
IOLoop.current().start()
- 当用户未登录直接访问index页面的时候,因为配置了验证登录(authenticated),所以他会直接跳转到login_url,并且url附带next参数
- 在登录页面获取这个next参数,如果没有默认为空,将这个参数传到页面的action中
- 在form表单提交后,在post方法里获取这个next参数,如果用户名和密码正确,并且存在这个next参数,就直接跳转到next参数所指向的url
- 若没有,就跳到正常登陆页面。
Session
- 使用前的配置:
- pip install redis
- pip install pycket
- settings配置:
from tornado.web import Application
from tornado.options import options
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
import handles settings = {
'template_path': 'templates',
'static_path': 'static',
'cookie_secret': 'summer',
'login_url': '/login',
'pycket': {
'engine': 'redis',
'storage': {
'host': 'localhost',
'port': 6379,
'db_sessions': 6,
'db_notifications': 11,
'max_connections': 3 * 10,
},
'cookies': {
'expires_days': 7,
'max_age': 100
},
},
} urlpatterns = [
(r'/login', handles.LoginHandle),
(r'/index', handles.IndexHandle),
] app = Application(handlers=urlpatterns, **settings) if __name__ == '__main__':
options.parse_command_line()
http = HTTPServer(app)
http.listen(1996)
IOLoop.current().start()如果redis有密码,在配置项里加一个password就可以了
- 使用:
from tornado.web import RequestHandler, authenticated
from pycket.session import SessionMixin class BaseHandle(RequestHandler, SessionMixin):
def get_current_user(self):
current_user = self.session.get('login')
if current_user:
return current_user class IndexHandle(BaseHandle):
@authenticated
def get(self):
self.write('index 页面') class LoginHandle(BaseHandle):
def get(self):
next_url = self.get_argument('next', '')
self.render('login.html', next_url=next_url) def post(self):
username = self.get_argument('username', '')
password = self.get_argument('password', '')
next_url = self.get_argument('next', '')
if username == password and next_url:
self.session.set('login', 'true')
self.redirect(next_url)
elif username == password:
self.set_secure_cookie('login', 'true')
self.write('登录成功!') - 导入SessionMinxin
- 让BaseHandle继承自SessionMinxin
- 设置session
- self.session.set(key, value)
- 获取session
- self.session.get(key)
xsrf:
在form表单的html里面加入{% module xsrf_form_html() %}即可
最新文章
- 数据结构:优先队列 基于list实现(python版)
- Django~automated tests
- js基础细节
- OC基础--block
- autotool相关:AC_ARG_ENABLE的用法
- VS2010使用TeeChart5的ColorGrid绘制一维距离像
- PL/SQL Developer连接远程Oracle数据库
- Duanxx的C++学习: 使用类没有被定义 原因及解决方法
- Hadoop Datanode 机器缺失 VD 问题修复尝试
- CSS边框外的小三角形+阴影效果的实现。
- CF 291E. Tree-String Problem [dfs kmp trie图优化]
- 解决浏览器兼容ES6特性
- spring cloud 随笔记录(1)-
- Harbor私有镜像仓库(上)
- CentOS 部署.net core 2.0 项目
- Unable to complete the scan for annotations for web application [/wrs] due to a StackOverflowError. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies.
- JS 数据类型和数据分析
- 详解Django中六个常用的自定义装饰器
- jmeter ---断言持续时间(Duration to Assert )和断言文件大小
- mysql监控工具sqlprofiler,类似sqlserver的profiler工具
热门文章
- Windows下EDK2环境的搭建以及经典的程序设计Print Hello World !-----(Linux下的待后续熟练了再更新)
- C++ 按行读取文件并打印
- BrowserSync(前端利器—保存代码后,自动刷新浏览器)
- [BUG]document.body.scrollTop=0不生效(回到顶部)
- 利用EPX Studio将C/S程序转成B/S的方法详解(在线模块方式)
- C# 微信 生活助手 空气质量 天气预报等 效果展示 数据抓取 (二)
- Ruby中的Hash(哈希),你可以理解为字典
- hdu1045 炮台的配置 dfs
- asp.net net::ERR_ABORTED 500 (Internal Server Error) 无法加载JS CSS等文件的解决方法
- Contest 152