tornado框架基础1

  • tornado框架的基本配置
 1 # -*- coding utf-8 -*-
 2 # coding=utf-8
 3 
 4 """"""
 5 """
 6 1.tornado框架的基本配置
 7 2.模板路径的配置
 8 3.静态文件的配置
 9 """
10 import tornado.ioloop
11 import tornado.web
12 
13 class MainHandler(tornado.web.RequestHandler):
14     # 以get方式(回车)请求时,执行get方法
15     def get(self):
16         # self.write('hello,world')
17         # render 会在当前目录找到s2.html,并且打开读取里面的内容返回给用户
18         # self.render('s2.html')
19         # 使用模板配置路径时
20         self.render('s4.html')
21 
22 settings = {
23     # 模板路径的配置,还要添加到路由映射那里
24 
25     'template_path':'template',  #存放html
26     'static_path':'static'   #存放css,javascript等静态文件
27 }
28 
29  # 路由映射,
30 application = tornado.web.Application([
31     # 如果是/index结尾,那么就会执行MainHandler
32     (r"/index",MainHandler),
33 ],**settings)
34 
35 if __name__ == '__main__':
36     application.listen(8888)
37     tornado.ioloop.IOLoop.instance().start()
View Code

配置路径我们用template_path来配置html路径,static_path来配置css,js等静态文件

s2.html在template路径下,c2.css在static路径下

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8     <h1>这是打开另一个HTML页面</h1>
 9 </body>
10 </html>
s2.html
1 h1{
2     font-size: 30px;
3     color: #4ab3ff;
4 }
c2.css

 

  • 提交实时更新功能
 1 # -*- coding utf-8 -*-
 2 # coding=utf-8
 3 
 4 import tornado.ioloop
 5 import tornado.web
 6 
 7 """
 8 提交实时更新功能
 9 
10 1.用self.get_argument()来获取用户数据
11 2.创建个全局变量列表来存放用户输入的数据
12 3.在s4.html里写模板语言,用于在页面展示刚刚输入的数据
13 4.用self.render()来把框架和s4.html联系起来,把用户输入的值传给html的模板语言
14 
15 
16 """
17 
18 # 创建一个全局变量来存放在s3.html里收到的用户输入值
19 INPUT_LIST = []
20 
21 class MainHandler(tornado.web.RequestHandler):
22     # 以get方式(回车)请求时,执行get方法
23     def get(self):
24       # 使用模板配置路径时
25       # 1.打开s3.html文件,读取内容
26       # 2.如果读取的内容中包含特殊语法,则通过
27       # inputList = INPUT_LIST 读取INPUT_LIST 里的内容到s3.html的inputList里
28 
29       # 一开始不能省略,inputlist=INPUT_LIST,不然执行s4.html时会找不到 inputlist
30       self.render('s4.html',inputlist=INPUT_LIST)
31 
32     # 以post方式请求时
33     def post(self,*args,**kwargs):
34         # 通过s3.html里的键’xxx‘取得用户输入的值
35         name = self.get_argument('xxx')
36         # print(name)
37         INPUT_LIST.append(name)
38         # self.write('hello,xiaobobo')
39         self.render('s4.html',inputlist=INPUT_LIST)
40 settings = {
41     # 模板路径的配置,还要添加到路由映射那里
42 
43     'template_path':'template',  #存放html
44 
45     'static_path':'static'   #存放css,javascript等静态文件
46 }
47 
48  # 路由映射,
49 application = tornado.web.Application([
50     # 如果是/index结尾,那么就会执行MainHandler
51     (r"/index",MainHandler),
52 ],**settings)
53 
54 if __name__ == '__main__':
55     application.listen(8888)
56     tornado.ioloop.IOLoop.instance().start()
View Code
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6      <!--<link rel="stylesheet" href="static/c2.css"/>-->
 7     <!--<link rel="stylesheet" href="{{static_url('/c2.css')}}">-->
 8 </head>
 9 <body>
10     <h1>提交内容:</h1>
11     <form action="/index" method="post">
12          <!--name定义的是键,用户输入的内容是值-->
13         <input type="text" name="xxx">
14         <!--提交后会把action的’/index‘添加到后缀-->
15         <input type="submit" value="提交">
16     </form>
17     <h1>展示内容:</h1>
18     <!--用来模块语言后注释好像有点问题........-->
19     <ul>
20         {% for i in inputlist %}
21         <li>{{i}}</li>
22         {% end %}
23     </ul>
24 </body>
25 </html>
s4.html
  • 自定义模板语言
 1 # -*- coding utf-8 -*-
 2 # coding=utf-8
 3 """"""
 4 """
 5 自定义模板语言:
 6         uimethod(函数)
 7         uimodule(类)
 8 
 9 
10 步骤:
11     1.建立uimethod.py,里面写了函数(要带self参数)/类(要继承UIModule)
12     2.在s5.html 的模板函数里写上自定义函数({{fun(nas)}})/类({% module custom() %})
13     3.在settings建立配置路径'ui_methods':mt,把uimethod.py,s5.html 和框架建立联系
14     4.用self.render()传参nas  (没传参的话可以不用用到这里)
15 
16 
17 """
18 import tornado.ioloop
19 import tornado.web
20 import uimethod as mt
21 import uimodule as md
22 
23 
24 # 创建一个全局变量来存放在s3.html里收到的用户输入值
25 INPUT_LIST = []
26 
27 class MainHandler(tornado.web.RequestHandler):
28     # 以get方式(回车)请求时,执行get方法
29     def get(self):
30       # 使用模板配置路径时
31       # 1.打开s3.html文件,读取内容
32       # 2.如果读取的内容中包含特殊语法,则通过
33       # inputList = INPUT_LIST 读取INPUT_LIST 里的内容到s3.html的inputList里
34 
35       self.render('s5.html',nas = 'NAS',inputlist=INPUT_LIST)
36 
37     # 以post方式请求时
38     def post(self,*args,**kwargs):
39         # 通过s3.html里的键’xxx‘取得用户输入的值
40         name = self.get_argument('xxx')
41         INPUT_LIST.append(name)
42         self.render('s5.html' ,nas = 'NAS',inputlist=INPUT_LIST)
43 
44 settings = {
45     # 模板路径的配置,还要添加到路由映射那里
46 
47     'template_path':'template',  #存放html
48     'static_path':'static',   #存放css,javascript等静态文件
49     'ui_methods':mt,
50     'ui_modules':md
51 }
52 
53  # 路由映射,
54 application = tornado.web.Application([
55     # 如果是/index结尾,那么就会执行MainHandler
56     (r"/index",MainHandler),
57 ],**settings)
58 
59 if __name__ == '__main__':
60     application.listen(8888)
61     tornado.ioloop.IOLoop.instance().start()
tornado_s3_module.py
 1 # -*- coding utf-8 -*-
 2 # coding=utf-8
 3 
 4 def fun(self,args):
 5     """
 6     返回小写参数
 7     :param args:
 8     :return: 小写的arg
 9     """
10     return args.lower()
uimethod.py
 1 # -*- coding utf-8 -*-
 2 # coding=utf-8
 3 
 4 from tornado.web import UIModule
 5 from tornado import escape
 6 
 7 # 模板类必须继承 UIModule
 8 class custom(UIModule):
 9     def render(self, *args, **kwargs):
10         return '这是自定义模板uimodule'
uimodule.py
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6      <link rel="stylesheet" href="static/c2.css"/>
 7     <!--<link rel="stylesheet" href="{{static_url('/c2.css')}}">-->
 8 </head>
 9 <body>
10     <h1>提交内容:</h1>
11     <form action="/index" method="post">
12         <input type="text" name="xxx">
13         <input type="submit" value="提交">
14     </form>
15     <h1>展示内容:</h1>
16     <h2>{{fun(nas)}}</h2>
17     <h2>{% module custom() %}</h2>
18     <ul>
19         {% for i in inputlist %}
20         <li>{{i}}</li>
21         {% end %}
22     </ul>
23 </body>
24 </html>
s5.html
  •  Ajax

    原生Ajax

 1 # -*- coding utf-8 -*-
 2 # coding=utf-8
 3 
 4 
 5 import tornado.ioloop
 6 import tornado.web
 7 
 8 """
 9 1.写处理函数,继承tornado.web.RequestHandler
10 2.设置模板路径
11 3.路由映射,tornado.web.Application([]),同时把模板路径设置添加进去
12 4.开启监听
13 
14 """
15 """
16 以ajax方式进行请求(不会刷新页面,不能跳转)
17 利用AJAX可以做:
18 1、注册时,输入用户名自动检测用户是否已经存在。
19 2、登陆时,提示用户名密码错误
20 3、删除数据行时,将行ID发送到后台,后台在数据库中删除,
21 数据库删除成功后,在页面DOM中将数据行也删除。(博客园)
22 """
23 
24 class LoginHandler(tornado.web.RequestHandler):
25     def get(self, *args, **kwargs):
26         self.render('login_aj.html')
27     def post(self, *args, **kwargs):
28         dic = {'status':True,'message':''}
29         user = self.get_argument('username')
30         pwd = self.get_argument('password')
31         if user == 'xiaobobo' and pwd == '123':
32             # 返回回应给页面,相当于login_aj的responseText
33             self.write('后台已收到!!')
34         else:
35             dic['status'] = False
36             dic['message'] = '用户名或密码错误!!'
37         import  json
38         # 将字典转化成字符串
39         self.write(json.dumps(dic))
40 
41 settings = {
42     'template_path':'template',
43 }
44 application = tornado.web.Application([
45     (r'/login_aj',LoginHandler), # ;login_aj后没有带.html
46 ],**settings)
47 
48 
49 
50 if __name__=='__main__':
51     application.listen(8888)
52     tornado.ioloop.IOLoop.instance().start()
tornado_ajax.py
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8         <input id="user" type="text" name="username">
 9         <input id="pwd" type="password" name="password">
10         <input type="button" value="登录" onclick="SubmitForm();">
11 
12         <script>
13             xhr = null;
14             function SubmitForm(){
15 
16 //通过XMLHttpRequest我们就可以往服务器端发送消息
17                 //创建了XMLHttpRequest对象
18                 xhr = new XMLHttpRequest();
19                 //用于创建请求
20                 //open(String method,String url,Boolen async)
21                 //     method:请求方式,url:要请求的地址,async:是否异步(一般为True)
22 //                xhr.open('GET','/login_aj',true);
23                 xhr.open('POST','login_aj',true);
24                 //当状态值readystate的值改变时自动触发执行其对应的函数(这里是fun())
25                 xhr.onreadystatechange = fun;//fun没有带括号
26                 //以post方式提交时要加上这个请求头
27                 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8');
28                 //发送请求
29 //                xhr.send();
30                 xhr.send("username="+document.getElementById('user').value+';password='+document.getElementById('pwd').value); //以post方式提交时,把把这些发送到服务器端
31             }
32             function fun() {
33                 //readystate是状态值,4代表发送成功且收到回响
34                 if(xhr.readyState==4){
35                     console.log(1);
36                     //responseText是回响的文本内容(20.5837                     console.log(xhr.responseText)
38                     var data = xhr.responseText;
39                     //js的json,把字符串转化成字典
40                     var ret_dict = JSON.parse(data);
41                     if(ret_dict.status){
42 
43                     }else{
44                         //在页面弹出警告
45                         alert(ret_dict.message)
46                     }
47                 }
48 
49             }
50         </script>
51 </body>
52 </html>
login_aj.html
  • cookie

 

 1 # -*- coding utf-8 -*-
 2 # coding=utf-8
 3 
 4 """
 5 1.创建基本页面index,manager,login
 6 2.设置特定的用户密码,已登录的话设置cookit('auth','1')
 7 3.cookit的auth为1时,再打开manager页面时才有内容显示,不然返回登录页面
 8 4.在manager页面按退出时,把auth设为0,此时相当于退出账号了
 9 5.添加模板语言是记得在get方法里初始化一下
10 """
11 import tornado.ioloop
12 import tornado.web
13 
14 class IndexHandler(tornado.web.RequestHandler):
15     def get(self, *args, **kwargs):
16         self.render('index.html')
17 
18 class LoginHandler(tornado.web.RequestHandler):
19     def get(self, *args, **kwargs):
20         self.render('login.html',status = '')
21 
22     def post(self, *args, **kwargs):
23         # 获取提交的用户账号,默认None
24         username = self.get_argument('username',None)
25         pwd = self.get_argument('password',None)
26         if username =='xiaobobo' and pwd =='123':
27             self.set_cookie('auth','1')
28             # redirect(),跳转页面
29             self.redirect('/manager')
30         else:
31             self.render('login.html',status = '登录失败')
32 
33 
34 class ManagerHandler(tornado.web.RequestHandler):
35     def get(self, *args, **kwargs):
36         co = self.get_cookie('auth')
37         if co == '1':
38             self.render('manager.html')
39         else:
40             self.redirect('/login')
41 
42 class LogoutHandler(tornado.web.RequestHandler):
43     def get(self, *args, **kwargs):
44         self.set_cookie('auth','0')
45         self.redirect('/login')
46 
47 
48 settings = {
49     'template_path':'template',
50 }
51 
52 appliacation  = tornado.web.Application([
53     (r'/index',IndexHandler),
54     (r'/login',LoginHandler),
55     (r'/manager',ManagerHandler),
56     (r'/logout',LogoutHandler),
57 ],**settings)
58 
59 if __name__ =="__main__":
60     appliacation.listen(8888)
61     tornado.ioloop.IOLoop.instance().start()
tornado_cookie.py

 

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8     <form action="/login" method="post">
 9         <input type="text" name="username">
10         <input type="password" name="password">
11         <input type="submit" value="登录">
12         <span style="color: red;">{{status}}</span>
13     </form>
14 </body>
15 </html>
login.html

 

 

 
posted @ 2017-05-17 00:26  yangyongbo  阅读(92)  评论(0)    收藏  举报