Tornado--搭建网页
Posted weilaixiaochaoren
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Tornado--搭建网页相关的知识,希望对你有一定的参考价值。
manage.py from tornado.ioloop import IOLoop # 处理I/O from tornado.web import RequestHandler # 处理请求 from tornado.web import Application # 实例化APP网页 USER_DICT = { ‘1‘: {‘name‘: ‘金超‘, ‘age‘: ‘22‘}, ‘2‘: {‘name‘: ‘小可‘, ‘age‘: ‘42‘}, ‘3‘: {‘name‘: ‘小鱼‘, ‘age‘: ‘32‘}, ‘4‘: {‘name‘: ‘小狗‘, ‘age‘: ‘52‘}, } # 中间件用于验证是否登录 class AuthHandler(object): def prepare(self): # name = self.get_cookie(‘xxxxx‘) #与Django方法做对比 name = self.set_secure_cookie(‘xxxxx‘) if not name: self.redirect(‘/login‘) # home页面 要先继承AuthHandler class HomeHandler(AuthHandler, RequestHandler): def get(self, *args, **kwargs): self.render(‘index.html‘, user_dict=USER_DICT, num=[11, 22, 33]) # index主页面 class IndexHandler(AuthHandler, RequestHandler): def get(self, *args, **kwargs): # 用user_dict带入参数传给页面 self.render(‘index.html‘, user_dict=USER_DICT, num=[11, 22, 33]) # login登录页面函数 class LoginHandler(RequestHandler): def get(self, *args, **kwargs): self.render(‘login.html‘, error=‘‘) def post(self, *args, **kwargs): # Tornado和Django做类比 # self.get_query_argument(‘user‘) request.GET.get(‘user‘) # self.get_query_arguments(‘user‘) request.GET.getlist(‘user‘) # self.get_body_argument(‘user‘) request.POST.get(‘user‘) # self.get_body_arguments(‘user‘) request.POST.getlist(‘user‘) user = self.get_body_argument(‘user‘) pwd = self.get_body_argument(‘pwd‘) if user == ‘alex‘ and pwd == ‘123‘: self.set_secure_cookie(‘xxxxx‘, user) self.redirect(‘/index‘) return self.render(‘login.html‘, error=‘用户名或密码错误‘) # 在settings中注册templates和中间件cookie settings = { ‘template_path‘: ‘templates‘, ‘cookie_secret‘: ‘asq3wurasldf‘ } # 在Application()方法里面写页面对应着函数 application = Application([ (‘/login‘, LoginHandler), (‘/index‘, IndexHandler), (‘/home‘, HomeHandler), ], **settings) # listen()方法可以监控端口和IP默认是本机 if __name__ == ‘__main__‘: application.listen(8888) IOLoop.instance().start()
以上是关于Tornado--搭建网页的主要内容,如果未能解决你的问题,请参考以下文章