【python之路43】tornado的用法(一)
一、tonado的代码
1、返回字符串
#!/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") def post(self): self.write("Hello, world") #路由映射 application = tornado.web.Application([ (r"/index", MainHandler), (r"/",MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
2、render返回html文件
#!/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") self.render('s1.html') #直接返回本录下的s1.html def post(self): self.write("Hello, world") #路由映射 application = tornado.web.Application([ (r"/index", MainHandler), (r"/",MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
3、html模板配置
#!/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") self.render('s1.html') #因为配置了全局文件路径,所以s1.html表示template/s1.html def post(self): self.write("Hello, world") #配置全局文件路径为:template settings = { 'template_path':'template', } #路由映射 application = tornado.web.Application([ (r"/index", MainHandler), (r"/",MainHandler), ],**settings) #**settings是让配置生效 if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
4、html中的静态路径配置
对html中引用的css和js文件的静态路径,需要在settings中配置,否则是无法找到文件的
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="static/common.css" /> </head> <body> <h1>hello world!</h1> <script src="static/oldboy.js"></script> </body> </html>
#!/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") self.render('s1.html') #因为配置了全局文件路径,所以s1.html表示template/s1.html def post(self): self.write("Hello, world") settings = { 'template_path':'template', #配置全局文件路径为:template 'static_path':'static', #配置html中的静态文件路径为static } #路由映射 application = tornado.web.Application([ (r"/index", MainHandler), (r"/",MainHandler), ],**settings) #**settings是让配置生效 if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
5、静态路径的前缀
实际存放路径见上面4的图片,只要定义了前缀,不管静态文件路径是什么,html中都需要用定义的前缀
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="sss/common.css" /> </head> <body> <h1>hello world!</h1> <script src="sss/oldboy.js"></script> </body> </html>
#!/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") self.render('s1.html') #因为配置了全局文件路径,所以s1.html表示template/s1.html def post(self): self.write("Hello, world") settings = { 'template_path':'template', #配置全局文件路径为:template 'static_path':'static', #配置html中的静态文件路径为static 'static_url_prefix':'/sss/', #静态路径的前缀,html实际是存放在static中,但html中引用是用sss } #路由映射 application = tornado.web.Application([ (r"/index", MainHandler), (r"/",MainHandler), ],**settings) #**settings是让配置生效 if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
6、post方法中self.get_argument接收对应的参数的值
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="sss/common.css" /> </head> <body> <form method="post" action="/index"> <input type="text" name="user"> <input type="submit" value="提交"> </form> <script src="sss/oldboy.js"></script> </body> </html>
#!/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") self.render('s1.html') #因为配置了全局文件路径,所以s1.html表示template/s1.html def post(self,*args,**kwargs): re = self.get_argument('user') #获取html传过来的user对应的参数值 print(re) #self.write("Hello, world") self.render('s1.html') #返回html settings = { 'template_path':'template', #配置全局文件路径为:template 'static_path':'static', #配置html中的静态文件路径为static 'static_url_prefix':'/sss/', #静态路径的前缀,html实际是存放在static中,但html中引用是用sss } #路由映射 application = tornado.web.Application([ (r"/index", MainHandler), (r"/",MainHandler), ],**settings) #**settings是让配置生效 if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
7、模板语言
两个知识点:
1)循环,item表示变量,用两个大括号表示
<ul>
{% for item in xx %}
<li>{{item}}</li>
{% end %}
</ul>
2)render可以加第2个参数,xx必须与html中模板语言中的xx一致,INPUT_LIST表示py中的列表
self.render('s1.html',xx = INPUT_LIST)
self.render('s1.html',xx = INPUT_LIST,yy = aa) #yy表示html中的变量yy,aa表示py中的变量
re = self.get_argument('user',None) #表示如果参数user不存在则re==None
下面例子,在页面文本框中增加内容立即显示在页面上:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="sss/common.css" /> </head> <body> <form method="post" action="/index"> <input type="text" name="user"> <input type="submit" value="提交"> </form> <ul> {% for item in xx %} <li>{{item}}</li> {% end %} </ul> <script src="sss/oldboy.js"></script> </body> </html>
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web INPUT_LIST = [] class MainHandler(tornado.web.RequestHandler): def get(self): #self.write("Hello, world") self.render('s1.html',xx = INPUT_LIST) #因为配置了全局文件路径,所以s1.html表示template/s1.html def post(self,*args,**kwargs): re = self.get_argument('user',None) #获取html传过来的user对应的参数值 if re: INPUT_LIST.append(re) #self.write("Hello, world") self.render('s1.html',xx = INPUT_LIST) #返回html settings = { 'template_path':'template', #配置全局文件路径为:template 'static_path':'static', #配置html中的静态文件路径为static 'static_url_prefix':'/sss/', #静态路径的前缀,html实际是存放在static中,但html中引用是用sss } #路由映射 application = tornado.web.Application([ (r"/index", MainHandler), (r"/",MainHandler), ],**settings) #**settings是让配置生效 if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
<ul>
{% for item in xx %}
{% if item == "alex" %}
<li style="color: red;">{{item}}</li>
{% else %}
<li>{{item}}</li>
{% end %}
{% end %}
</ul>
8、模板语言自定义函数
1)目录结构如下:
2)在s1.py同级目录中增加uimethod.py,并在uimethod.py中定义方法:
#!/usr/bin/env python # -*- coding:utf-8 -*- def func(self,arg): return "123"
3)在s1.py中导入uimethod.py,import uimethod as mt,并在settings中进行配置
'ui_methods':mt,html中可以使用函数了<h1>{{func(npm)}}</h1>
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web import uimethod as mt INPUT_LIST = [] class MainHandler(tornado.web.RequestHandler): def get(self): #self.write("Hello, world") self.render('s1.html',xx = INPUT_LIST, npm="NPM") #因为配置了全局文件路径,所以s1.html表示template/s1.html def post(self,*args,**kwargs): re = self.get_argument('user',None) #获取html传过来的user对应的参数值 if re: INPUT_LIST.append(re) #self.write("Hello, world") self.render('s1.html',xx = INPUT_LIST) #返回html settings = { 'template_path':'template', #配置全局文件路径为:template 'static_path':'static', #配置html中的静态文件路径为static 'static_url_prefix':'/sss/', #静态路径的前缀,html实际是存放在static中,但html中引用是用sss 'ui_methods':mt, #自定义函数路径配置,表示来自mt,mt是从uimethod导入的 } #路由映射 application = tornado.web.Application([ (r"/index", MainHandler), (r"/",MainHandler), ],**settings) #**settings是让配置生效 if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="sss/common.css" /> </head> <body> <form method="post" action="/index"> <input type="text" name="user"> <input type="submit" value="提交"> </form> <ul> {% for item in xx %} {% if item == "alex" %} <li style="color: red;">{{item}}</li> {% else %} <li>{{item}}</li> {% end %} {% end %} </ul> <h1>{{func(npm)}}</h1> <script src="sss/oldboy.js"></script> </body> </html>
结果如下图:
执行顺序:
A、执行s1.py,
self.render('s1.html',xx = INPUT_LIST, npm="NPM") #因为配置了全局文件路径,所以s1.html表示template/s1.html
B、执行s1.html中的模板语言,遇到自定义函数,npm = "NPM"
<h1>{{func(npm)}}</h1>
C、根据settings配置和导入模块执行uimethod.py函数,arg = npm = "NPM"
def func(self,arg):
return arg
9、模板语言自定义类
1)目录结构如下
2)在s1.py同级目录中增加uimodule.py,并在uimodule.py中定义方法:
#!/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>sunshuhai</h1>') return 'Hello world!'
3)在s1.py中导入uimodule.py,import uimodule as md,并在settings中进行配置
'ui_modules':md,html中可以使用函数了<h1>{% module custom() %}</h1>
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web import uimethod as mt import uimodule as md INPUT_LIST = [] class MainHandler(tornado.web.RequestHandler): def get(self): #self.write("Hello, world") self.render('s1.html',xx = INPUT_LIST, npm="NPM") #因为配置了全局文件路径,所以s1.html表示template/s1.html def post(self,*args,**kwargs): re = self.get_argument('user',None) #获取html传过来的user对应的参数值 if re: INPUT_LIST.append(re) #self.write("Hello, world") self.render('s1.html',xx = INPUT_LIST) #返回html settings = { 'template_path':'template', #配置全局文件路径为:template 'static_path':'static', #配置html中的静态文件路径为static 'static_url_prefix':'/sss/', #静态路径的前缀,html实际是存放在static中,但html中引用是用sss 'ui_methods':mt, #自定义函数路径配置,表示来自mt,mt是从uimethod导入的 'ui_modules':md, #自定义类路径配置,表示来自md,md是从uimodule导入的 } #路由映射 application = tornado.web.Application([ (r"/index", MainHandler), (r"/",MainHandler), ],**settings) #**settings是让配置生效 if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="sss/common.css" /> </head> <body> <form method="post" action="/index"> <input type="text" name="user"> <input type="submit" value="提交"> </form> <ul> {% for item in xx %} {% if item == "alex" %} <li style="color: red;">{{item}}</li> {% else %} <li>{{item}}</li> {% end %} {% end %} </ul> <h1>{{func(npm)}}</h1> <h1>{% module custom() %}</h1> <script src="sss/oldboy.js"></script> </body> </html>
4)最终显示结果如下:
10、模板中默认的字段、函数
在模板中默认提供了一些函数、字段、类以供模板使用:
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
1)static_url配件html静态文件路径,具有缓存功能,静态文件更新后才重新下载
<link rel="stylesheet" href="{{static_url('common.css')}}" />
<script src="{{static_url('oldboy.js')}}"></script>
代码如下:
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web import uimethod as mt import uimodule as md INPUT_LIST = [] class MainHandler(tornado.web.RequestHandler): def get(self): #self.write("Hello, world") self.render('s1.html',xx = INPUT_LIST, npm="NPM") #因为配置了全局文件路径,所以s1.html表示template/s1.html def post(self,*args,**kwargs): re = self.get_argument('user',None) #获取html传过来的user对应的参数值 if re: INPUT_LIST.append(re) #self.write("Hello, world") self.render('s1.html',xx = INPUT_LIST) #返回html settings = { 'template_path':'template', #配置全局文件路径为:template 'static_path':'static', #配置html中的静态文件路径为static 'static_url_prefix':'/sss/', #静态路径的前缀,html实际是存放在static中,但html中引用是用sss 'ui_methods':mt, #自定义函数路径配置,表示来自mt,mt是从uimethod导入的 'ui_modules':md, #自定义类路径配置,表示来自md,md是从uimodule导入的 } #路由映射 application = tornado.web.Application([ (r"/index", MainHandler), (r"/",MainHandler), ],**settings) #**settings是让配置生效 if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="{{static_url('common.css')}}" /> </head> <body> <form method="post" action="/index"> <input type="text" name="user"> <input type="submit" value="提交"> </form> <ul> {% for item in xx %} {% if item == "alex" %} <li style="color: red;">{{item}}</li> {% else %} <li>{{item}}</li> {% end %} {% end %} </ul> <h1>{{func(npm)}}</h1> <h1>{% module custom() %}</h1> <script src="{{static_url('oldboy.js')}}"></script> </body> </html>
#!/usr/bin/env python # -*- coding:utf-8 -*- def func(self,arg): return arg
#!/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>sunshuhai</h1>') return 'Hello world!'
#h{ color: red; }
console.log('aaa')
11、模板语言的实质
模板语言的实质是将html字符串分隔之后,再进行的拼接,如下图:
下面代码是执行有变量的字符串函数:
#!/usr/bin/env python # -*- coding:utf-8 -*- code =""" def helocute(): return "name %s,age %d" %(name,data[0],) """ func = compile(code,'<string>','exec') nameplace = {'name':'sunshuhai','data':[18,73,84]} exec(func,nameplace) #将函数func(此时func指向helocute函数)加入到字典nameplace result = nameplace['helocute']() print(result) #结果:name sunshuhai,age 18
12、跳转页面
self.redirect("/login.html")
13、Cookie的用法
1)、设置Cookie
def set_cookie(self, name, value, domain=None, expires=None, path="/",expires_days=None, **kwargs):
name,value 键值对
domain 域名
expires 到期时间,time.time()+10 表示10秒后过期,time.time()表示立即过期
expires_days 表示多少天后过期
2)得到cookie
co = self.get_cookie("auth")
3)加密的cookie,配置settings,字符串为加盐字符串,可以随便设置
settings = {
'cookie_secret':'qerqrdfd12dds',
}
设置加密cookie:
self.set_secure_cookie("auth","wuzheng")
获取加密cookie:
co = self.get_secure_cookie("auth") #结果返回b'wuzheng',是字节类型
co1 = str(co,encoding='utf-8') #转化为字符串类型,co1="wuzheng"
4)实例:
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web import time class MainHandler(tornado.web.RequestHandler): def get(self): #self.write("Hello, world") self.render('index.html') #因为配置了全局文件路径,所以s1.html表示template/s1.html class ManagerHandler(tornado.web.RequestHandler): def get(self,*args,**kwargs): #co = self.get_cookie("auth") co = self.get_secure_cookie("auth") #返回b'wuzheng',是字节类型 co1 = str(co,encoding='utf-8') #转化为字符串类型 print(co1) if co1 == "wuzheng": self.render('manager.html') else: self.redirect("\login") class LogInHandler(tornado.web.RequestHandler): def get(self,*args,**kwargs): self.render('login.html',status="") def post(self,*args,**kwargs): username = self.get_argument("username",None) password = self.get_argument("password",None) if username == "sunshuhai" and password == "123": #self.set_cookie("auth","1") #self.set_cookie("auth,","wuzheng",expires_days=7) #expires_days表示7天后cookie过期 #r = time.time() + 10 #self.set_cookie("auth,","wuzheng",expires=r) #表示10秒后过期 #self.set_cookie("auth,","wuzheng",expires=time.time()) #表示立即过期 self.set_secure_cookie("auth","wuzheng") self.render("index.html") else: self.render('login.html',status = "用户名密码错误!") class LogOutHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): self.set_cookie("auth","0") #将cookie中auth的值改掉 self.redirect("/login") settings = { 'template_path':'views', #配置全局文件路径为:template 'cookie_secret':'qerqrdfd12dds', } #路由映射 application = tornado.web.Application([ (r"/index", MainHandler), (r"/manager",ManagerHandler), (r"/login",LogInHandler), (r"/logout",LogOutHandler), ],**settings) #**settings是让配置生效 if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>我的首页</h1> </body> </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"> <input type="password" name="password"> <input type="submit" value="登陆"> <span style="color:red;">{{status}}</span> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <a href="/logout">退出登陆</a> <h1>银行卡余额为:-1500元</h1> </body> </html>
14、Ajax用法
1)概述
Ajax主要就是用【XmlHttpRequest】对象来完成请求的操作,该对象在主流浏览器中均存在(除另类IE),其实是不刷新 页面的前提下偷偷的通过浏览器向服务器发送请求
2)XmlHttpRequest对象的主要方法
a ) void open(String method,String url,Boolen async)
用于创建请求
参数:
method 请求方式(字符串类型),如POST、GET、DELETE
url 要请求的地址(字符串类型)
async 是否异步(布尔类型),默认为true,如果设置为false那么页面会hold住,完成前不能做其他的事情,所以一般设置为默认的true
b)void send(String body)
用于发送请求
c) void setRequestHeader(String header,String value)
用于设置请求头,参数:header:请求头key(字符串类型)
参数:value:请求头的value(字符串类型)
d)、String getAllResponseHeaders()
获取所有响应头
e)void abort()
终止请求
2)XmlHttpRequest对象的主要属性
a)Nmber ReadyState
状态值(整型):
详细:
0-未初始化,尚未调用open() 方法
1-启动,调用了open()方法,未调用send()方法
2-发送,调用了send()方法,未收到相应
3-接收,已经接收到部分响应数据
4-完成,已经接收都全响应部数据
b)Function onreadystatechange
当readyState的值改变时自动触发执行其对应的函数(回调函数)
c)String responseText
服务器返回的数据(字符串类型)
d)XmlDocument responseXML
服务器返回的数据(Xml对象)
e)Number states
状态码(整数),如:200 404 。。。。
f)String statesText
状态文本(字符串),如:OK、NotFound......
3)原生Ajax的实例:
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web class LogInHandler(tornado.web.RequestHandler): def get(self,*args,**kwargs): self.render('login.html') def post(self,*args,**kwargs): dic = {"result":True,"message":""} user = self.get_argument("username") pwd = self.get_argument("password") #print(user,pwd) if user == "sunshuhai" and pwd == "123": pass else: dic["result"]=False dic["message"]="登陆失败" import json dicStr = json.dumps(dic) self.write(dicStr) settings = { 'template_path':'views', #配置全局文件路径为:template } #路由映射 application = tornado.web.Application([ (r"/login",LogInHandler), ],**settings) #**settings是让配置生效 if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input id="t1" type="text" name="username"> <input id="t2" type="password" name="password"> <input type="button" value="登陆" onclick="SubmitForm()"> <script> xhr = null; function SubmitForm() { xhr = new XMLHttpRequest(); xhr.onreadystatechange=func; xhr.open("POST","/login"); xhr.setRequestHeader("content-type","application/x-www-form-urlencoded"); //xhr.send("username=alex;password=123"); var user = document.getElementById("t1").value //获得用户名 var pwd = document.getElementById('t2').value //获得密码 xhr.send("username=" +user+ ";password=" + pwd) } function func() { console.log(xhr.readyState) //每次readyState的变化该函数都会捕获到 if(xhr.readyState == 4){ console.log(xhr.responseText); //请求完毕后服务器返回的内容 var resContent = xhr.responseText; var resJson = JSON.parse(resContent); //将获取的内容转化为js,json对象 if(resJson["result"]){ alert("登陆成功!") }else{ alert("登陆失败!") } } } </script> </body> </html>
4)JQuery下的Ajax实例
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web class LogInHandler(tornado.web.RequestHandler): def get(self,*args,**kwargs): self.render('login.html') def post(self,*args,**kwargs): dic = {"result":True,"message":""} user = self.get_argument("username") pwd = self.get_argument("password") #print(user,pwd) if user == "sunshuhai" and pwd == "123": pass else: dic["result"]=False dic["message"]="登陆失败" import json dicStr = json.dumps(dic) self.write(dicStr) settings = { 'template_path':'views', #配置全局文件路径为:template 'static_path':'static', } #路由映射 application = tornado.web.Application([ (r"/login",LogInHandler), ],**settings) #**settings是让配置生效 if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input id="t1" type="text" name="username"> <input id="t2" type="password" name="password"> <input type="button" value="登陆" onclick="SubmitForm()"> <script src= {{static_url('jquery.js')}}></script> <script> function SubmitForm() { $.post('/login',{"username":$('#t1').val(),"password":$('#t2').val()},function (callback) { console.log(callback) //callback为服务器响应的结果 }) } </script> </body> </html>