1、tonado的代码css
一、返回字符串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") 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()
二、render返回html文件 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") 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()
三、html模板配置jquery
#!/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()
四、html中的静态路径配置web
对html中引用的css和js文件的静态路径,须要在settings中配置,不然是没法找到文件的npm
<!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()
五、静态路径的前缀json
实际存放路径见上面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()
六、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()
七、模板语言服务器
两个知识点:
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>
八、模板语言自定义函数
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
九、模板语言自定义类
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)最终显示结果以下:
十、模板中默认的字段、函数
在模板中默认提供了一些函数、字段、类以供模板使用:
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
: for handler.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')
十一、模板语言的实质
模板语言的实质是将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
十二、跳转页面
self.redirect("/login.html")
1三、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>
1四、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>