tornado 路由、模板語言、session

一:tornado路由系統:javascript

一、面向資源編程:css

場景:當咱們給別人提供api的時候,每每提供url。好比:電影票api:html

1 http://movie.jd.com/book_ticket:預訂電影票。
2 http://movie.jd.com/get_ticket:獲取電影票。
3 http://movie.jd.com/del_ticket:退電影票。

 若是咱們給別人提供如上url api的話,那麼咱們和使用接口方的人須要維護這幾個url。相應的成本較高。前端

由於如上的緣由,有人根據url(統一資源定位符)提出設想:java

咱們是否能夠根據用戶的請求的method來給用戶不一樣的服務呢?python

for example:jquery

1 def get(*arg):
2     pass  #查詢電影票
3 def post(*arg):
4     passs #訂購電影票
5 def  put(*arg):
6     pass#退電影票。

根據方法的不一樣,處理不一樣的功能。這種提供api方式咱們叫作面向資源編程。也叫作restulful(Representational State Transfer縮寫,表現層狀態轉化:http://www.ruanyifeng.com/blog/2011/09/restful)web

tornado 天生支持restulful。根據用戶的請求的不一樣,觸發不一樣的函數。之後再給別人提供接口或者在使用別人的接口的時候,須要使用這種面向資源的方式。redis

二、2級域名,tornado在url劃分的時候,比django更加友好,django是在主域名後面接着2級域名好比:http://www.liumeide.com:8888/cmdb/index 配置使用include 進行業務分類url。數據庫

而tornado直接使用二級域名來區分不一樣的業務:http://cmd.liumeide.com:8888/index cmdb服務,http://www.liumeide.com:8888/index  主站服務。http://monitor.liumeide.com:8888/index  監控服務。

京東也是這麼區分,只不過京東各個系統是相對獨立的。

主站:

團購:

配置:

1 application.add_handlers("cmd.liumeide.com",#從新設置url使用add_handlers方法,第一個參數是2級域名名稱,後面是url列表。
2     [
3         (r"/index", CmdbHandler)
4     ]

完整代碼:

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 import tornado.ioloop
 5 import tornado.web
 6 
 7 
 8 class MainHandler(tornado.web.RequestHandler):
 9     def get(self):
10         self.write("mian web")
11 class CmdbHandler(tornado.web.RequestHandler):
12     def get(self):
13         # self.write("Hello, world")
14         self.write('cmdb')
15 setting={
16     'template_path':'template',#設置模板文件路徑。
17     'static_path':'static'#設置靜態資源路徑
18 }
19 application = tornado.web.Application([
20     (r"/index", MainHandler),
21 ],**setting)
22 application.add_handlers("cmd.liumeide.com",#從新設置url使用add_handlers方法,第一個參數是2級域名名稱,後面是url列表。
23     [
24         (r"/index", CmdbHandler)
25     ]
26 )
27 
28 if __name__ == "__main__":
29     application.listen(8888)
30     tornado.ioloop.IOLoop.instance().start()

 note:

  1. 他們公用一個setting配置。!!!

 效果:

二:模板語言:

在模板語言中,for循環支持break、continue等語法,語法形式:{%break%} 也支持python的一些方法.好比lenth等。

也支持母板和子板,只是結束符是end 而不是 endblock。

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
 5     <title>老男孩</title>
 6     <link href="{{static_url("css/common.css")}}" rel="stylesheet" />
 7     {% block CSS %}{% end %}
 8 </head>
 9 <body>
10 
11     <div class="pg-header">
12 
13     </div>
14     
15     {% block RenderBody %}{% end %}
16    
17     <script src="{{static_url("js/jquery-1.8.2.min.js")}}"></script>
18     
19     {% block JavaScript %}{% end %}
20 </body>
21 </html> 

子板:

 1 {% extends 'layout.html'%}
 2 {% block CSS %}
 3     <link href="{{static_url("css/index.css")}}" rel="stylesheet" />
 4 {% end %}
 5 
 6 {% block RenderBody %}
 7     <h1>Index</h1>
 8 
 9     <ul>
10     {%  for item in li %}
11         <li>{{item}}</li>
12     {% end %}
13     </ul>
14 
15 {% end %}
16 
17 {% block JavaScript %}
18     
19 {% end %}
20 

導入:也有頁面的導入

header.html

1 <div>
2     <ul>
3         <li>1024</li>
4         <li>42區</li>
5     </ul>
6 </div>
7 
8 header.html
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
 5     <title>老男孩</title>
 6     <link href="{{static_url("css/common.css")}}" rel="stylesheet" />
 7 </head>
 8 <body>
 9 
10     <div class="pg-header">
11         {% include 'header.html' %}
12     </div>
13     
14     <script src="{{static_url("js/jquery-1.8.2.min.js")}}"></script>
15     
16 </body>
17 </html>
18 
19 index.html 

自定製功能:uimethod和uimodlues。

對比:

  • 2者均可以給前端傳遞參數,不過method只能傳遞方法函數,而uimodules傳遞是類,經過類定義不一樣的方法,前端調用不方法函數。
  • uimodules能夠給前端傳遞js、css等。

uimethod:

首先須要定義個模塊好比:co.py. 而後寫方法:

1 def f1(self,a):
2     return a

在配置setting中註冊:

1 import  co
2 setting={
3     'template_path':'template',#設置模板文件路徑。
4     'static_path':'static',#設置靜態資源路徑
5     'ui_methods':co,#註冊
6 } 

後臺代碼:

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 import tornado.ioloop
 5 import tornado.web
 6 import  co
 7 
 8 class MainHandler(tornado.web.RequestHandler):
 9     def get(self):
10         self.render('main.html')
11 setting={
12     'template_path':'template',#設置模板文件路徑。
13     'static_path':'static',#設置靜態資源路徑
14     'ui_methods':co,
15 }
16 application = tornado.web.Application([
17     (r"/index", MainHandler),
18 ],**setting)
19 
20 if __name__ == "__main__":
21     application.listen(8888)
22     tornado.ioloop.IOLoop.instance().start()

前端頁面引用:注意是2個大括號相似於變量的引用。

1 <h1> {{f1(2)}}</h1>

效果:

uimodles:

一、定義模塊文件:oc.py

2:寫類和方法。

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 from tornado.web import UIModule
 4 from tornado import escape
 5 
 6 class custom(UIModule):#注意須要繼承模塊。
 7 
 8     def render(self, *args, **kwargs):
 9         return '<h1> 2</h1>'
10     def javascript_files(self):
11         return 'http://111.js'
12     def css_files(self):
13         return 'http://222.css'

3:前端註冊

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 
 4 import tornado.ioloop
 5 import tornado.web
 6 import  co
 7 import oc
 8 class MainHandler(tornado.web.RequestHandler):
 9     def get(self):
10         self.render('main.html')
11 setting={
12     'template_path':'template',#設置模板文件路徑。
13     'static_path':'static',#設置靜態資源路徑
14     'ui_methods':co,
15     'ui_modules':oc,
16 }
17 application = tornado.web.Application([
18     (r"/index", MainHandler),
19 ],**setting)
20 
21 if __name__ == "__main__":
22     application.listen(8888)
23     tornado.ioloop.IOLoop.instance().start()

4:頁面引用:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <h1> {{f1(2)}}</h1>
 9 {% module  custom(22) %}<!--注意頁面的引用方式不同uimodule是須要關鍵字module 以及百分號和uimethod的不一樣-->
10 </body>
11 </html>

效果:

三:tornado session

設計思想:

  • 服務器端產生隨機字符串並寫入客戶端,下次客戶端請求的時候攜帶這個隨機字符串。
  • 服務器端須要儲存該隨機字符串,並額外保存用戶其餘信息,好比:用戶名。
  • 客戶端每次請求,須要判斷客戶端是否有已經寫入cookie。
  • 每次訪問,更新cookie過時時間。而不是每次都寫入隨機字符串。
  • session信息能夠存儲在內存、數據庫、redis等。設置過時時間,按期清理,釋放磁盤空間。
  • 對於僞造的cookie,從新寫入客戶端。
  • 隨機字符串能夠用time來生成md5寫入客戶端。

代碼實現:

 1 #!/usr/bin/env python
 2 #-*-coding:utf-8-*-
 3 # author:liumeide
 4 import hashlib
 5 import time
 6 Session_Info={}
 7 
 8 def md5():
 9     m = hashlib.md5()
10     m.update(bytes(str(time.time()),encoding='utf-8'))
11     return m.hexdigest()
12 
13 class Session:
14     def __init__(self,handler):
15         self.handler=handler
16     def check_se(self):
17         current_time = time.time()
18         ret = self.handler.get_cookie('cookie_str', None)  # 自定義cookie key值。下次訪問的請求的時候根據這個key來獲取cookie的隨機字符串。
19         if ret:  # 在有效的cookie設置範圍內。
20             if ret in Session_Info.keys():  # 合法的cookie
21                 cookie_str = ret
22                 return True
23             else:  # 非法僞造或者過時的cookie。
24                 cookie_str = md5()
25         else:  # 第一次訪問請求設置cookie
26             cookie_str = md5()
27             Session_Info[cookie_str] = {}
28             self.handler('cookie_str', cookie_str, expires=current_time + 200)  # 不管你是第一次仍是屢次請求,cookie都須要從新寫入瀏覽器。須要設置過時時間。
29 
30     def __getitem__(self, item):#獲取cookie
31         pass
32     def __setitem__(self, key, value):#設置cookie
33         pass
34     def __delitem__(self, key):#刪除ookie
35         pass
相關文章
相關標籤/搜索