Tornado Web框架
Tornado 是 FriendFeed 使用的可擴展的非阻塞式 web 服務器及其相關工具的開源版本。這個 Web 框架看起來有些像web.py 或者 Google 的 webapp,不過為了能有效利用非阻塞式服務器環境,這個 Web 框架還包含了一些相關的有用工具 和優化。
Tornado 和現在的主流 Web 服務器框架(包括大多數 Python 的框架)有着明顯的區別:它是非阻塞式服務器,而且速度相當快。得利於其 非阻塞的方式和對 epoll 的運用,Tornado 每秒可以處理數以千計的連接,這意味着對於實時 Web 服務來說,Tornado 是一個理想的 Web 框架。我們開發這個 Web 服務器的主要目的就是為了處理 FriendFeed 的實時功能 ——在 FriendFeed 的應用里每一個活動用戶都會保持着一個服務器連接。(關於如何擴容 服務器,以處理數以千計的客戶端的連接的問題,請參閱 C10K problem。)
安裝:
pip3 install tornado
源碼安裝
https://pypi.python.org/packages/source/t/tornado/tornado-4.3.tar.gz
框架使用
快速啟動一個web
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
- 第三步:服務器接受請求,application 根據請求的url交由對應的類處理該請求
- 第四步:類接受到請求之后,根據請求方式(post / get / delete ...)的不同調用並執行相應的方法
- 第五步:write方法返回值的字符串內容發送瀏覽器
tornado自定義settings
從上面快速啟動例子發現,可以使用一個py腳本即可啟動web服務,但如果涉及到html、js、css等文件,全部放到一塊,顯得非常雜亂,我們可以參考django的目錄結構進行配置tornado
我們可以定一個配置字典,命名為settings,然后將相關配置放到字典中,最后應用到tornado即可
例子:
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): #self.write("Hello, world") self.render('index.html') #使用render 返回一個html #自定義settings settings = { "template_path":"templates", "static_path":"statics", } application = tornado.web.Application([ (r"/index", MainHandler), ],**settings) #應用到tornado中 if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
tornado的路由系統
路由系統其實就是 url 和 類 的對應關系,這里不同於其他框架,其他很多框架均是 url 對應 函數,Tornado中每個url對應的是一個類。
簡單多條路由
簡單多條路由實現,其實就是在tornado.web.Application對象中傳遞多個url和對應的類即可
如下,在原來的基礎上,增加一條/cmdb 的url
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): #self.write("Hello, world") self.render('index.html') class CMDBHandler(tornado.web.RequestHandler): def get(self): self.write('CMDB') settings = { "template_path":"templates", "static_path":"statics", 'static_url_prefix': '/static/', } application = tornado.web.Application([ (r"/index", MainHandler), (r"/cmdb", CMDBHandler), ],**settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
原生支持二級域名
tornado 還可以支持自動將主域名的子目錄轉換為二級域名,如 www.fuzengjie.cn/cmdb --> cmdb.fuzengjie.cn
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write('hello word') class CmdbHandler(tornado.web.RequestHandler): def get(self): self.write('Cmdb') class IndexHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') settings = { 'template_path' :'templates', } application = tornado.web.Application([ (r'/main',MainHandler), (r'/index',IndexHandler), ],**settings) #添加二級域名對應的url application.add_handlers('cmdb.fuzengjie.cn',[ (r'/main',CmdbHandler) ]) if __name__ == '__main__': application.listen(8000) tornado.ioloop.IOLoop.instance().start()
動態路由
tornado同樣支持動態路由,即通過正則匹配URL,然后傳參到對應的類中
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self,user,pwd): self.write("Hello,%s, is %s" %(user,pwd)) class CMDBHandler(tornado.web.RequestHandler): def get(self,num): self.write('CMDB is %s' %num) settings = { "template_path":"templates", "static_path":"statics", 'static_url_prefix': '/static/', } application = tornado.web.Application([ (r"/index/(?P<user>.*)/(?P<pwd>.*)", MainHandler), (r"/cmdb/(\w+)", CMDBHandler), ],**settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
原生支持restful api
所謂的restful api就是使用同一個api,根據請求的方式不同,來實現不同的api功能,即
- 每一個URI代表一種資源;
- 客戶端和服務器之間,傳遞這種資源的某種表現層;
- 客戶端通過四個HTTP動詞(get、post、delete、put),對服務器端資源進行操作,實現"表現層狀態轉化;
由於tornado 默認就是根據請求的方式來調用對應的方法,如用戶是get請求,handler會自動執行類中get的方法,用戶是post請求,會自動執行類中的post方法。所以tornado原生就支持restful api
模版語言
Tornao中的模板語言和django中類似,模板引擎將模板文件載入內存,然后將數據嵌入其中,最終獲取到一個完整的字符串,再將字符串返回給請求者。
Tornado 的模板支持“控制語句”和“表達語句”,控制語句是使用 {% 和 %} 包起來的 例如 {% if len(items) > 2 %}。表達語句是使用 {{ 和 }} 包起來的,例如 {{ items[0] }}。
控制語句和對應的 Python 語句的格式基本完全相同。我們支持 if、for、while 和 try,這些語句邏輯結束的位置需要用 {% end %} 做標記。還通過 extends 和 block 語句實現了模板繼承。這些在 template 模塊 的代碼文檔中有着詳細的描述。
注:在使用模板前需要在setting中設置模板路徑:"template_path" : "tpl"
tornado的模版語言和python的語法差不多
基本使用
- python代碼
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.render("index.html", list_info = [11,22,33]) application = tornado.web.Application([ (r"/index", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
app.py
- html
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>付增傑</title> <link href="{{static_url("css/common.css")}}" rel="stylesheet" /> </head> <body> <div> <ul> {% for item in list_info %} <li>{{item}}</li> {% end %} </ul> </div> <script src="{{static_url("js/jquery-1.8.2.min.js")}}"></script> </body> </html>
- 其他方法
在模板中默認提供了一些函數、字段、類以供模板使用:
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同樣支持模版,即定義好一個模板,在其他頁面直接可以應用
- 模板
layout.html
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>老男孩</title> <link href="{{static_url("css/common.css")}}" rel="stylesheet" /> {% block CSS %}{% end %} </head> <body> <div class="pg-header"> </div> {% block RenderBody %}{% end %} <script src="{{static_url("js/jquery-1.8.2.min.js")}}"></script> {% block JavaScript %}{% end %} </body> </html>
- 引入
{% extends 'layout.html'%} {% block CSS %} <link href="{{static_url("css/index.css")}}" rel="stylesheet" /> {% end %} {% block RenderBody %} <h1>Index</h1> <ul> {% for item in li %} <li>{{item}}</li> {% end %} </ul> {% end %} {% block JavaScript %} {% end %}
導入
tornado 也可以導入其他html文件
- header.html
<div> <ul> <li>1024</li> <li>42區</li> </ul> </div>
- index
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>老男孩</title> <link href="{{static_url("css/common.css")}}" rel="stylesheet" /> </head> <body> <div class="pg-header"> {% include 'header.html' %} </div> </body> </html>
UIMothed 和UIModule
- UIMothed 和python的simple_tag類似,用於在渲染template的時候自定義方法
- UIModule 用於在渲染template時,生成template中的的一些元素
使用
-
創建uimothed和uimodule:
uimothed和uimodule自定義方法其實就是python的函數和類。注意:自定義uimothed是在腳本中直接定義的函數(方法)即可,自定義uimodule是在腳本中定義的類
uimothed: xo.py
def test_uimothed(self,arg): #注意,定義方法的時候需要加self
return 'test_' + arg
uimodule: ox.py
from tornado.web import UIModule from tornado import escape class custom(UIModule): def render(self, *args, **kwargs): return escape.xhtml_escape('<h1>uimodule test</h1>')
- 注冊 先導入剛才定義的腳本,然后在settings中加載
#!/usr/bin/env python import tornado.ioloop import tornado.web import xo import ox class MainHandler(tornado.web.RequestHandler): def get(self,user,pwd): self.write("Hello,%s, is %s" %(user,pwd)) class CMDBHandler(tornado.web.RequestHandler): def get(self,num): self.write('CMDB is %s' %num) class TestHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') settings = { "template_path":"templates", "static_path":"statics", "ui_methods":xo, "ui_modules":ox, } application = tornado.web.Application([ (r"/index/(?P<user>.*)/(?P<pwd>.*)", MainHandler), (r"/cmdb/(\w+)", CMDBHandler), (r"/test",TestHandler), ],**settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
- 使用
注意uimothed 直接使用{% uimothed%}進行調用,uimodule使用{ module uimodule}調用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link src="/statics/index.css"> </head> <body> <h1>index</h1> <p class=test>index for test</p> {% module custom(123) %} {{ test_uimothed('ui_mothed') }} //注意由於tornado的模版語言遵循python語法,所以傳參數的時候字符串需要加引號,否則會當變量處理 </body> </html>
-
UIModule補充
UIModule 自定義類中支持的方法
- render:返回字符串
- javascript_files 在前端生成 塊
- embedded_javascript 在前端生成js的代碼
- css_files 在前端生成塊
- embedded_css 在前端生成css的代碼
Cookie
Tornado中可以對cookie進行操作,並且還可以對cookie進行簽名以放置偽造。
- 基本操作
class MainHandler(tornado.web.RequestHandler): def get(self): if not self.get_cookie("mycookie"): self.set_cookie("mycookie", "myvalue") self.write("Your cookie was not set yet!") else: self.write("Your cookie was set!")
- 加密cookie
Cookie 很容易被惡意的客戶端偽造。加入你想在 cookie 中保存當前登陸用戶的 id 之類的信息,你需要對 cookie 作簽名以防止偽造。Tornado 通過 set_secure_cookie 和 get_secure_cookie 方法直接支持了這種功能。 要使用這些方法,你需要在創建應用時提供一個密鑰,名字為 cookie_secret。 你可以把它作為一個關鍵詞參數傳入應用的設置中
class MainHandler(tornado.web.RequestHandler): def get(self): if not self.get_secure_cookie("mycookie"): self.set_secure_cookie("mycookie", "myvalue") self.write("Your cookie was not set yet!") else: self.write("Your cookie was set!") application = tornado.web.Application([ (r"/", MainHandler), ], cookie_secret="61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=")
- 加密cookie 內部加密解密
def _create_signature_v1(secret, *parts): hash = hmac.new(utf8(secret), digestmod=hashlib.sha1) for part in parts: hash.update(utf8(part)) return utf8(hash.hexdigest()) # 加密 def _create_signature_v2(secret, s): hash = hmac.new(utf8(secret), digestmod=hashlib.sha256) hash.update(utf8(s)) return utf8(hash.hexdigest()) def create_signed_value(secret, name, value, version=None, clock=None, key_version=None): if version is None: version = DEFAULT_SIGNED_VALUE_VERSION if clock is None: clock = time.time timestamp = utf8(str(int(clock()))) value = base64.b64encode(utf8(value)) if version == 1: signature = _create_signature_v1(secret, name, value, timestamp) value = b"|".join([value, timestamp, signature]) return value elif version == 2: # The v2 format consists of a version number and a series of # length-prefixed fields "%d:%s", the last of which is a # signature, all separated by pipes. All numbers are in # decimal format with no leading zeros. The signature is an # HMAC-SHA256 of the whole string up to that point, including # the final pipe. # # The fields are: # - format version (i.e. 2; no length prefix) # - key version (integer, default is 0) # - timestamp (integer seconds since epoch) # - name (not encoded; assumed to be ~alphanumeric) # - value (base64-encoded) # - signature (hex-encoded; no length prefix) def format_field(s): return utf8("%d:" % len(s)) + utf8(s) to_sign = b"|".join([ b"2", format_field(str(key_version or 0)), format_field(timestamp), format_field(name), format_field(value), b'']) if isinstance(secret, dict): assert key_version is not None, 'Key version must be set when sign key dict is used' assert version >= 2, 'Version must be at least 2 for key version support' secret = secret[key_version] signature = _create_signature_v2(secret, to_sign) return to_sign + signature else: raise ValueError("Unsupported version %d" % version) # 解密 def _decode_signed_value_v1(secret, name, value, max_age_days, clock): parts = utf8(value).split(b"|") if len(parts) != 3: return None signature = _create_signature_v1(secret, name, parts[0], parts[1]) if not _time_independent_equals(parts[2], signature): gen_log.warning("Invalid cookie signature %r", value) return None timestamp = int(parts[1]) if timestamp < clock() - max_age_days * 86400: gen_log.warning("Expired cookie %r", value) return None if timestamp > clock() + 31 * 86400: # _cookie_signature does not hash a delimiter between the # parts of the cookie, so an attacker could transfer trailing # digits from the payload to the timestamp without altering the # signature. For backwards compatibility, sanity-check timestamp # here instead of modifying _cookie_signature. gen_log.warning("Cookie timestamp in future; possible tampering %r", value) return None if parts[1].startswith(b"0"): gen_log.warning("Tampered cookie %r", value) return None try: return base64.b64decode(parts[0]) except Exception: return None def _decode_fields_v2(value): def _consume_field(s): length, _, rest = s.partition(b':') n = int(length) field_value = rest[:n] # In python 3, indexing bytes returns small integers; we must # use a slice to get a byte string as in python 2. if rest[n:n + 1] != b'|': raise ValueError("malformed v2 signed value field") rest = rest[n + 1:] return field_value, rest rest = value[2:] # remove version number key_version, rest = _consume_field(rest) timestamp, rest = _consume_field(rest) name_field, rest = _consume_field(rest) value_field, passed_sig = _consume_field(rest) return int(key_version), timestamp, name_field, value_field, passed_sig def _decode_signed_value_v2(secret, name, value, max_age_days, clock): try: key_version, timestamp, name_field, value_field, passed_sig = _decode_fields_v2(value) except ValueError: return None signed_string = value[:-len(passed_sig)] if isinstance(secret, dict): try: secret = secret[key_version] except KeyError: return None expected_sig = _create_signature_v2(secret, signed_string) if not _time_independent_equals(passed_sig, expected_sig): return None if name_field != utf8(name): return None timestamp = int(timestamp) if timestamp < clock() - max_age_days * 86400: # The signature has expired. return None try: return base64.b64decode(value_field) except Exception: return None def get_signature_key_version(value): value = utf8(value) version = _get_version(value) if version < 2: return None try: key_version, _, _, _, _ = _decode_fields_v2(value) except ValueError: return None return key_version
- 實現原理
- 寫cookie過程:
- 將值進行base64加密
- 對除值以外的內容進行簽名,哈希算法(無法逆向解析)
- 拼接 簽名 + 加密值
- 讀cookie過程:
- 讀取 簽名 + 加密值
- 對簽名進行驗證
- base64解密,獲取值內容
- 寫cookie過程:
CSRF
tornado 同樣支持CSRF,和django類似
- 配置
只需要在settings中開啟csrf
settings = { "xsrf_cookies": True, } application = tornado.web.Application([ (r"/", MainHandler), (r"/login", LoginHandler), ], **settings)
- 使用普通表單
<form action="/new_message" method="post"> {{ xsrf_form_html() }} //在這里會自動生成xsrf的密鑰 <input type="text" name="message"/> <input type="submit" value="Post"/> </form>
- 使用ajax
function getCookie(name) { var r = document.cookie.match("\\b" + name + "=([^;]*)\\b"); return r ? r[1] : undefined; } jQuery.postJSON = function(url, args, callback) { args._xsrf = getCookie("_xsrf"); $.ajax({url: url, data: $.param(args), dataType: "text", type: "POST", success: function(response) { callback(eval("(" + response + ")")); }}); };
使用 - AJAX
注:Ajax使用時,本質上就是去獲取本地的cookie,攜帶cookie再來發送請求
異步
tornado 默認是單進程單線程的,當第一個請求還沒處理完,第二個請求會等待第一個請求完成,而tornado的異步實現了單進程單線程處理多並發的請求,其內部原理就是使用的協程
裝飾器 + Future 從而實現Tornado的異步非阻塞
class AsyncHandler(tornado.web.RequestHandler): @gen.coroutine def get(self): future = Future() future.add_done_callback(self.doing) yield future # 或 # tornado.ioloop.IOLoop.current().add_future(future,self.doing) # yield future def doing(self,*args, **kwargs): self.write('async') self.finish()
當發送GET請求時,由於方法被@gen.coroutine裝飾且yield 一個 Future對象,那么Tornado會等待,等待用戶向future對象中放置數據或者發送信號,如果獲取到數據或信號之后,就開始執行doing方法。
異步非阻塞體現在當在Tornaod等待用戶向future對象中放置數據時,還可以處理其他請求。
注意:在等待用戶向future對象中放置數據或信號時,此連接是不斷開的。
- httpclient類庫
Tornado提供了httpclient類庫用於發送Http請求,其配合Tornado的異步非阻塞使用。
class AsyncHandler(tornado.web.RequestHandler): @gen.coroutine def get(self): from tornado import httpclient http = httpclient.AsyncHTTPClient() yield http.fetch("http://www.google.com", self.endding) def endding(self, response): print(len(response.body)) self.write('ok') self.finish()
