1.pip install pycket
2.pip install redis
防止xsrf攻击只需在模板form标签加入:
{% module xsrf_form_html() %}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <form method="post" action="/login?next={{ nextname }}" > {% module xsrf_form_html %} 用户名</br> <input type="text" name="name" /><br> <input type="text" name="passwd" /><br> <input type="submit" value="提交"> </form> </body> </html>
#coding:utf-8 import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import time from tornado.options import define,options from data.sqlalchemy08 import User,session from tornado.web import authenticated from pycket.session import SessionMixin define('port',default=8000,help='run port',type=int) define('version',default='0.0.1',help='version 0.0.1',type=str) def auth(fun): def wrapper(self,*agrs,**kwargs): id=self.get_secure_cookie('ID') if id: return fun(self,*args,**kwargs) else: self.redirect('/login') return auth #设置继承 class BaseHandeler(tornado.web.RequestHandler,SessionMixin): def get_current_user(self): # current_user=self.get_secure_cookie('ID') current_user=self.session.get('user') if current_user: return current_user else: return None class IndexHandler(BaseHandeler): #用auth装饰,可省去大量重复代码,在需要登录的地方调用就可以 # @auth #从写认证方法中的current_user # def get_current_user(self): # current_user = self.get_secure_cookie('ID') # if current_user: # return current_user # else: # return None #用tornado自带的认证,需在底部app设置加上登录界面login_url,否则报错,为了再次复用,写个父类 @authenticated # @tornado.web.authenticated def get(self): # id=self.get_secure_cookie('ID') # if id: # self.write('登录成功') # else: # self.redirect('/login') self.write('登录成功') class LoginHandler(BaseHandeler): def get(self): #self.render('08login.html', error=None) nextname=self.get_argument('next','') self.render('11authencated.html',nextname=nextname) def post(self): nextname = self.get_argument('next', '') username = User.by_name(self.get_argument('name', '')) passwd = self.get_argument('passwd', '') if username and username[0].passwd == passwd: #self.set_secure_cookie('ID',username[0].username,max_age=100) self.session.set('user',username[0].username) # self.write('登录成功-----') # time.sleep(3) self.redirect(nextname) else: self.redirect('/login') if __name__ == "__main__": tornado.options.parse_command_line() # print(options.port) app=tornado.web.Application( handlers=[ (r'/index',IndexHandler), (r'/login',LoginHandler), ], template_path='templates', static_path='static', login_url='/login', debug=True, cookie_secret='aaa5555sssss', #配置redis设置 pycket={ 'engine':'redis', 'storage':{ 'host':'localhost', 'port':6379, 'db_sessions':5, 'db_notifications':2**31, }, 'cookies':{ 'expires_days':30, 'max_age':100 }, }, ) #固定写法: http_server=tornado.httpserver.HTTPServer(app) http_server.listen(options.port) tornado.ioloop.IOLoop.instance().start()