总结
settings里添加 login_url, cookie_secret, xsrf_cookies
模板form添加 {% module xsrf_form_html() %}
cookie使用
set_cookie
set_secure_cookie
get_cookie
get_secure_cookie
#-*- coding: utf-8 -*-
import tornado.httpserver
import tornado.ioloop
import tornado.web
import os
class HomeHandler(tornado.web.RequestHandler):
def test_string(self, msg):
msg = msg.decode('utf-8')
return '<a href=%s>%s</a>' % (msg,msg)
def get(self, *args, **kwargs):
self.ui['test_function'] = self.test_string
txt = '<h1>err</h1>'
self.render('index.html', error =txt, list=[1,2,4])
#4
class LoginHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.render('login.html')
def post(self, *args, **kwargs):
#6 使用set_secure_cookie
self.set_secure_cookie('user', self.get_argument('user', None))
# import pdb
# pdb.set_trace()
self.write('Successully set cookie')
#3
class OtherHtmlHandler(tornado.web.RequestHandler):
#cookie是后台存储用户信息的数据结构
#把用户信息存储在cookie中
def get_current_user(self):
#7 使用get_secure_cookie
user = self.get_secure_cookie('user')
return user
def get(self, page):
# import pdb
# pdb.set_trace()
if not self.current_user:
#self.redirect("/login.html")
self.redirect(self.settings['login_url'])
return
pagename = page + '.html'
path = os.path.join(self.settings['static_path'], pagename)
self.render(pagename)
class OtherHandler(tornado.web.RequestHandler):
def get(self, page, extension):
pagename = page + '.' + extension
path = os.path.join(self.settings['static_path'], pagename)
if extension != 'html':
with open(path) as f:
self.write(f.read())
class CustomApp(tornado.web.Application):
def __init__(self):
handles = [
(r'/$', HomeHandler),
(r'/login.html', LoginHandler),
# (r'/auth/login', FormHandler),
#1
(r'/(.+?)\.html', OtherHtmlHandler),
(r'/(.+?)\.(.+)', OtherHandler),
]
settings = {
#取得本文件所在的目录与templates组合一个路径
'template_path':os.path.join(os.path.dirname(__file__), 'templates'),
'static_path':os.path.join(os.path.dirname(__file__), 'static'),
'blog_title': "tornado blog",
#2 设置跳转到登陆页面
'login_url': '/login.html',
#5 防止cookie被偷窥和伪造
'cookie_secret':"2379874hsdhf0234990sdhsaiuofyasop977djdj",
#8防止跨站攻击 CSRF
#模板中表单里也要加{% module xsrf_form_html() %}
'xsrf_cookies':True,
}
super(CustomApp, self).__init__(handles, **settings)
if __name__ == '__main__':
# 实例化一个httpserver对象
#app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
app = CustomApp()
http_server = tornado.httpserver.HTTPServer(app)
# 监听8888 套接字端口
http_server.listen(8000)
# 启动事件循环
tornado.ioloop.IOLoop.instance().start()