tornado初级篇
Posted linu
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了tornado初级篇相关的知识,希望对你有一定的参考价值。
一:tornado代码初始化,入门基础
创建python文件包
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/index", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
第一步:执行脚本,监听 8888 端口
第二步:浏览器客户端访问 /index --> http://127.0.0.1:8888/index
第三步:服务器接受请求,并交由对应的类处理该请求
第四步:类接受到请求之后,根据请求方式(post / get / delete ...)的不同调用并执行相应的方法
第五步:方法返回值的字符串内容发送浏览器
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web from tornado import httpclient from tornado.web import asynchronous from tornado import gen import uimodules as md import uimethods as mt class MainHandler(tornado.web.RequestHandler): @asynchronous @gen.coroutine def get(self): print ‘start get ‘ http = httpclient.AsyncHTTPClient() http.fetch("http://127.0.0.1:8008/post/", self.callback) self.write(‘end‘) def callback(self, response): print response.body settings = { ‘template_path‘: ‘template‘, ‘static_path‘: ‘static‘, ‘static_url_prefix‘: ‘/static/‘, ‘ui_methods‘: mt, ‘ui_modules‘: md, } application = tornado.web.Application([ (r"/index", MainHandler), ], **settings) if __name__ == "__main__": application.listen(8009) tornado.ioloop.IOLoop.instance().start()
二、连接数据库,登录版本的tornado
#!/usr/bin/env python #-*-coding: utf-8 -*- import tornado.ioloop import tornado.web import pymysql class MainHandler(tornado.web.RequestHandler): def get(self): #get 和 post的区别,get,url中传输数据 self.render("login.html") def post(self, *args, **kwargs): # 获取用户提交的数据 username = self.get_argument(‘username‘, None) # 获取数据,通过,get_argument pwd = self.get_argument(‘pwd‘, None) # 创建数据库连接 conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘‘, db=‘db1‘) cursor = conn.cursor() # temp = "select name from userinfo where name=‘%s‘ and password = ‘%s‘" % (username, pwd) # 不安全 # print(temp) effect_row = cursor.execute("select name from userinfo where name= %s and password = %s ", (username, pwd,)) #安全些 result = cursor.fetchone() conn.commit() cursor.close() conn.close() if result: self.write(‘登录成功‘) else: self.write(‘登录失败‘) settings = { "template_path":"template", # 模板路径 ‘static_path‘: ‘static‘, # 静态文件的处理,即对css文件的处理 ‘static_url_prefix‘: ‘/static/‘, # 静态文件的前缀 } # 路由映射,路由系统 application = tornado.web.Application([ (r"/login", MainHandler), # ==》login.html ],**settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
2. login.html 文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login" method="post"> <input type="text" name="username" placeholder="用户" /> <input type="text" name="pwd" placeholder="密码" /> <input type="submit" /> </form> </body> </html>
三、在tornado中定义模板路径
在模板中默认提供了一些函数、字段、类以供模板使用:
escape
:tornado.escape.xhtml_escape
的別名xhtml_escape
:tornado.escape.xhtml_escape
的別名url_escape
:tornado.escape.url_escape
的別名json_encode
:tornado.escape.json_encode
的別名squeeze
:tornado.escape.squeeze
的別名linkify
:tornado.escape.linkify
的別名datetime
: Python 的datetime
模组handler
: 当前的RequestHandler
对象request
:handler.request
的別名current_user
:handler.current_user
的別名locale
:handler.locale
的別名_
:handler.locale.translate
的別名static_url
: forhandler.static_url
的別名xsrf_form_html
:handler.xsrf_form_html
的別名
Tornado默认提供的这些功能其实本质上就是 UIMethod 和 UIModule,我们也可以自定义从而实现类似于Django的simple_tag的功能:
1、定义
def tab(self): return ‘UIMethod‘
#!/usr/bin/env python # -*- coding:utf-8 -*- from tornado.web import UIModule from tornado import escape class custom(UIModule): def render(self, *args, **kwargs): return escape.xhtml_escape(‘<h1>user</h1>‘) #return escape.xhtml_escape(‘<h1>user</h1>‘)
2、注册
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web from tornado.escape import linkify import uimodules as md import uimethods as mt class MainHandler(tornado.web.RequestHandler): def get(self): self.render(‘index.html‘) settings = { ‘template_path‘: ‘template‘, ‘static_path‘: ‘static‘, ‘static_url_prefix‘: ‘/static/‘, ‘ui_methods‘: mt, ‘ui_modules‘: md, } application = tornado.web.Application([ (r"/index", MainHandler), ], **settings) if __name__ == "__main__": application.listen(8009) tornado.ioloop.IOLoop.instance().start()
3、使用
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <link href="{{static_url("commons.css")}}" rel="stylesheet" /> </head> <body> <h1>hello</h1> </body> </html>
四、关于tornado的cookie的认识
cookie值即是用户登录系统后所有产生的cookie值,保留这种用户的客户端,再次登录只需要验证cookie值,就可登录成功
1、定义一个首页
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>首页</h1> </body> </html>
2、定义登录页
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login" method="post"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="submit" value="登录" /> <span style="color: red">{{status_text}}</span> </form> </body> </html>
3、定义登录后才见到的页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="/logout">退出</a> <h1>银行卡余额1000</h1> </body> </html>
4、主程序。逻辑关系的呈现
#!/usr/bin/env python #-*-coding: utf8-*- # 项目一,关于cookis的认识 # viems文件夹 # index.html 主页 # login.html 登录页 # manager.html 登录能看的页 # __init__.py # runmain.py import tornado.ioloop import tornado.web # 定义首页 class IndexHandler(tornado.web.RequestHandler): def get(self,*args,**kwargs): self.render(‘index.html‘,) # 定义需要登录才能看到的页面,即需要有cookie class ManagerHandler(tornado.web.RequestHandler): def get(self,*args,**kwargs): co = self.get_cookie(‘auth‘) if co == ‘1‘: self.render(‘manager.html‘,) else: self.redirect("/login") # 定义登录后出现的退出程序 class LogoutHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): self.get_cookie(‘auth‘,‘0‘) self.render(‘/login‘ ) # 定义登录页,如果成功,则产生cookie class LoginHandler(tornado.web.RequestHandler): def get(self,*args,**kwargs): self.render(‘login.html‘,status_text="") def post(self, *args, **kwargs): username = self.get_argument(‘username‘,None) pwd = self.get_argument(‘password‘,None) if username == ‘user‘ and pwd == "sb": self.set_cookie(‘auth‘,‘1‘) self.redirect(‘/manager‘) else: self.render(‘login.html‘,status_text="登录失败") settings = { ‘template_path‘:‘viems‘, } application = tornado.web.Application([ (r"/index", IndexHandler), (r"/login", LoginHandler), (r"/manager", ManagerHandler), (r"/logout",LogoutHandler) ], **settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
运行程序,检验其逻辑关系,各个页面。127.0.0.1:8888/index ,127.0.0.1:8888/login,各个cookie值
5、补充cookie保存的时间,增加cookie值带的用户名
class LoginHandler(tornado.web.RequestHandler): def get(self,*args,**kwargs): self.render(‘login.html‘,status_text="") def post(self, *args, **kwargs): username = self.get_argument(‘username‘,None) pwd = self.get_argument(‘password‘,None) check = self.get_argument(‘auto‘,None) if username == ‘user‘ and pwd == "sb": if check: self.set_cookie(‘username‘,username,expires_days=7) self.set_cookie(‘auth‘,‘1‘,expires_days=7) else: r = time.time() + 100 self.set_cookie(‘auth‘,‘1‘,expires=r) self.set_cookie(‘username‘, username, expires=r) self.redirect(‘/manager‘) else: self.render(‘login.html‘,status_text="登录失败")
<body> <form action="/login" method="post"> <input type="text" name="username" /> <input type="password" name="password" /> <input type="checkbox" name="auto" value="1" />7天免登录 <input type="submit" value="登录" /> <span style="color: red">{{status_text}}</span> </form> </body>
以上是关于tornado初级篇的主要内容,如果未能解决你的问题,请参考以下文章
[AndroidStudio]_[初级]_[配置自动完成的代码片段]