簡介javascript
Tornado 是 FriendFeed 使用的可擴展的非阻塞式 web 服務器及其相關工具的開源版本。這個 Web 框架看起來有些像web.py 或者 Google 的 webapp,不過爲了能有效利用非阻塞式服務器環境,這個 Web 框架還包含了一些相關的有用工具 和優化。css
Tornado 和如今的主流 Web 服務器框架(包括大多數 Python 的框架)有着明顯的區別:它是非阻塞式服務器,並且速度至關快。得利於其 非阻塞的方式和對epoll的運用,Tornado 每秒能夠處理數以千計的鏈接,這意味着對於實時 Web 服務來講,Tornado 是一個理想的 Web 框架。咱們開發這個 Web 服務器的主要目的就是爲了處理 FriendFeed 的實時功能 ——在 FriendFeed 的應用裏每個活動用戶都會保持着一個服務器鏈接。html
Tornado安裝java
pip3 install tornado
初識Tornadopython
首先打開pycharm,新建一個乾淨的projectjquery
新建一個py文件:git
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): # 相似於Django裏面的CBV def get(self): # get方法 self.write("Hello, world") application = tornado.web.Application([ # 相似於Django裏面的路由系統 (r"/index", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start() # 啓動
運行文件並打開瀏覽器訪問網址:web
運行該腳本,依次執行:ajax
整個過程其實就是在建立一個socket服務端並監聽8888端口,當請求到來時,根據請求中的url和請求方式(post、get或put等)來指定相應的類中的方法來處理本次請求,在上述demo中只爲url爲http://127.0.0.1:8888/index的請求指定了處理類MainHandler(具體如何尋找見下文)。因此,在瀏覽器上訪問:http://127.0.0.1:8888/index,則服務器給瀏覽器就會返回 Hello,world ,不然返回 404: Not Found(tornado內部定義的值), 即完成一次http請求和響應。正則表達式
經典的Login案例
首先,建立模版文件夾和模版文件:
login.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST" action="/login"> <input type="text" name="username" /> <input type="submit" value="提交" /> </form> </body> </html>
新建一個路由:
(r"/login", LoginHandler),
新建CBV:
class LoginHandler(tornado.web.RequestHandler): def get(self): self.render("login.html") def post(self, *args, **kwargs): # 獲取url中以GET形式傳遞的數據 self.get_query_argument() self.get_query_arguments() # 去請求體中獲取傳遞的數據 self.get_body_argument() self.get_body_arguments() # 去get&post雙方去取數據 user = self.get_argument('username') print(user) self.redirect('www.baidu.com')
註冊模版文件路徑:
# 申明settings,字典格式 settings = { 'template_path': 'tmp' } # 註冊進tornado內部 application = tornado.web.Application([ (r"/index", MainHandler), (r"/login", LoginHandler), ], **settings)
總體app文件:
#!/usr/bin/env python3 # encoding: utf-8 # Author: Dandy import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") class LoginHandler(tornado.web.RequestHandler): def get(self): self.render("login.html") def post(self, *args, **kwargs): # 獲取url中以GET形式傳遞的數據 self.get_query_argument() self.get_query_arguments() # 去請求體中獲取傳遞的數據 self.get_body_argument() self.get_body_arguments() # 去get&post雙方去取數據 user = self.get_argument('username') print(user) self.redirect('www.baidu.com') settings = { 'template_path': 'tmp' } application = tornado.web.Application([ (r"/index", MainHandler), (r"/login", LoginHandler), ], **settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
此時即可執行
關於靜態文件
首先添加靜態文件夾,並放入一張圖片
靜態路徑註冊:
settings = { 'template_path': 'tmp', 'static_path': 'statics' }
login頁面加入圖片、注意如下路徑寫的是static,標準用法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="POST" action="/login"> <input type="text" name="username" /> <input type="submit" value="提交" /> </form> <img src="/static/炫雅.jpeg" /> </body> </html>
此時訪問頁面
那能不能不用static做爲靜態文件夾名稱呢?
答案固然是能夠的,只須要這樣註冊:
settings = { 'template_path': 'tmp', 'static_path': 'statics', 'static_url_prefix': '/jingtai/', # 這裏就是用戶自定義的靜態路徑名稱 }
再去修改login網頁裏的就行了。
上面簡單的介紹了一下totornado的一些基本運用搭建。如今花點篇幅詳細的解決各個模塊的基本問題。
路由系統從前面Django的學習過程當中不難總結出來,其實就是url和視圖函數的對應關係。固然啦,在Django裏面,有FBV和CBV的概念;而在tornado每一個url對應的函數均是一個類,即CBV。
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") class StoryHandler(tornado.web.RequestHandler): def get(self, story_id): self.write("You requested the story " + story_id) class HomeHandler(tornado.web.RequestHandler): def get(self): self.write("dandy") application = tornado.web.Application([ (r"/index", MainHandler), (r"/story/([0-9]+)", StoryHandler), ]) application.add_handlers(r"^a\.com$", [ (r"/", HomeHandler), # 路由a.com:8888/ ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
Tornado中原生支持二級域名的路由,如:
Tornao中的模板語言和django中相似,模板引擎將模板文件載入內存,而後將數據嵌入其中,最終獲取到一個完整的字符串,再將字符串返回給請求者。
Tornado 的模板支持「控制語句」和「表達語句」,控制語句是使用 {%
和 %}
包起來的 例如 {% if len(items) > 2 %}
。表達語句是使用 {{
和 }}
包起來的,例如 {{ items[0] }}
。
控制語句和對應的 Python 語句的格式基本徹底相同。咱們支持 if
、for
、while
和 try
,這些語句邏輯結束的位置須要用 {% end %}
作標記。還經過 extends
和 block
語句實現了模板繼承。
注:在使用模板前須要在setting中設置模板路徑:"template_path" : "tpl"
一、基本使用
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.render("index.html", list_info=[11, 22, 33], key1='value1') settings = { 'template_path': 'tmp' } application = tornado.web.Application([ (r"/index", MainHandler), ], **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 href='{{static_url("css/common.css")}}' rel="stylesheet" /> </head> <body> <h1>{{ key1 }}</h1> <ul> {% for item in list_info %} {% if item > 12 %} <li>{{ item }}</li> {% end %} {% end %} </ul> </body> </html>
相似於static_url的其餘方法
在模板中默認提供了一些函數、字段、類以供模板使用: 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 的別名
二、母版
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>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> layout.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 %}
三、導入小標籤
<div> <ul> <li>dandy</li> <li>durant</li> </ul> </div>
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title></title> </head> <body> <div class="pg-header"> {% include 'header.html' %} </div> </body> </html>
四、模版函數擴展UIMethod&UIModule
a、申明
def tab(self): return 'UIMethod'
from tornado.web import UIModule from tornado import escape class custom(UIModule): def render(self, *args, **kwargs): return escape.xhtml_escape('<h1>wuzdandz</h1>')
b、註冊
import uimodules as md import uimethods as mt settings = { 'template_path': 'template', 'static_path': 'static', 'ui_methods': mt, 'ui_modules': md, }
c、使用
<body> {% module custom(123) %} <br> {{ tab() }} </body>
注意一下這幾個方法:
embedded_css/javascript 用來產生css或js語句的
javascript/css_files用來產生link指向文件
對於靜態文件,能夠配置靜態文件的目錄和前段使用時的前綴,而且Tornaodo還支持靜態文件緩存。
settings = { 'template_path': 'template', 'static_path': 'static', 'static_url_prefix': '/static/', } application = tornado.web.Application([ (r"/index", MainHandler), ], **settings)
<img src="/static/炫雅.jpeg" /> <link href='{{static_url("commons.css")}}' rel="stylesheet" />
def get_content_version(cls, abspath): """Returns a version string for the resource at the given path. This class method may be overridden by subclasses. The default implementation is a hash of the file's contents. .. versionadded:: 3.1 """ data = cls.get_content(abspath) hasher = hashlib.md5() if isinstance(data, bytes): hasher.update(data) else: for chunk in data: hasher.update(chunk) return hasher.hexdigest()
Tornado中能夠對cookie進行操做,而且還能夠對cookie進行簽名以放置僞造。
一、基本操做
class MainHandler(tornado.web.RequestHandler): def get(self): if not self.get_cookie("username"): # 獲取cookie self.set_cookie("username", "dandy") # 設置cookie 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=")
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的本質是:
寫cookie過程: 將值進行base64加密 對除值之外的內容進行簽名,哈希算法(沒法逆向解析) 拼接 簽名 + 加密值 讀cookie過程: 讀取 簽名 + 加密值 對簽名進行驗證 base64解密,獲取值內容
注:許多API驗證機制和安全cookie的實現機制相同。
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): login_user = self.get_secure_cookie("login_user", None) if login_user: self.write(login_user) else: self.redirect('/login') class LoginHandler(tornado.web.RequestHandler): def get(self): self.current_user() self.render('login.html', **{'status': ''}) def post(self, *args, **kwargs): username = self.get_argument('name') password = self.get_argument('pwd') if username == 'wupeiqi' and password == '123': self.set_secure_cookie('login_user', '武沛齊') self.redirect('/') else: self.render('login.html', **{'status': '用戶名或密碼錯誤'}) settings = { 'template_path': 'template', 'static_path': 'static', 'static_url_prefix': '/static/', 'cookie_secret': 'aiuasdhflashjdfoiuashdfiuh' } application = tornado.web.Application([ (r"/index", MainHandler), (r"/login", LoginHandler), ], **settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web class BaseHandler(tornado.web.RequestHandler): def get_current_user(self): return self.get_secure_cookie("login_user") class MainHandler(BaseHandler): @tornado.web.authenticated def get(self): login_user = self.current_user self.write(login_user) class LoginHandler(tornado.web.RequestHandler): def get(self): self.current_user() self.render('login.html', **{'status': ''}) def post(self, *args, **kwargs): username = self.get_argument('name') password = self.get_argument('pwd') if username == 'wupeiqi' and password == '123': self.set_secure_cookie('login_user', '武沛齊') self.redirect('/') else: self.render('login.html', **{'status': '用戶名或密碼錯誤'}) settings = { 'template_path': 'template', 'static_path': 'static', 'static_url_prefix': '/static/', 'cookie_secret': 'aiuasdhflashjdfoiuashdfiuh', 'login_url': '/login' } application = tornado.web.Application([ (r"/index", MainHandler), (r"/login", LoginHandler), ], **settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
三、javascript操做cookie
因爲Cookie保存在瀏覽器端,因此在瀏覽器端也可使用JavaScript來操做Cookie。
/* 設置cookie,指定秒數過時 */ function setCookie(name,value,expires){ var temp = []; var current_date = new Date(); current_date.setSeconds(current_date.getSeconds() + 5); document.cookie = name + "= "+ value +";expires=" + current_date.toUTCString(); }
固然更推薦使用jquery cookie來操做cookie
Tornado中的跨站請求僞造和Django中的類似
一、啓用設置
settings = { "xsrf_cookies": True, } application = tornado.web.Application([ (r"/", MainHandler), (r"/login", LoginHandler), ], **settings)
二、表單
<form action="/new_message" method="post"> {% raw xsrf_form_html() %} <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使用時,本質上就是去獲取本地的cookie,攜帶cookie再來發送請求
一、form表單上傳
<body> <form name="form" action="/index" method="POST" enctype="multipart/form-data" > <input name="fafafa" id="my_file" type="file" /> <input type="submit" value="提交" /> </form> </body>
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') def post(self, *args, **kwargs): file_metas = self.request.files["fafafa"] # print(file_metas) for meta in file_metas: file_name = meta['filename'] with open(file_name,'wb') as up: up.write(meta['body']) settings = { 'template_path': 'template', } application = tornado.web.Application([ (r"/index", MainHandler), ], **settings) if __name__ == "__main__": application.listen(8000) tornado.ioloop.IOLoop.instance().start()
二、ajax上傳
<body> <input type="file" id="img" /> <input type="button" onclick="UploadFile();" /> <script> function UploadFile(){ var fileObj = document.getElementById("img").files[0]; var form = new FormData(); form.append("k1", "v1"); form.append("fff", fileObj); var xhr = new XMLHttpRequest(); xhr.open("post", '/index', true); xhr.send(form); } </script> </body>
<body> <input type="file" id="img" /> <input type="button" onclick="UploadFile();" /> <script> function UploadFile(){ var fileObj = $("#img")[0].files[0]; var form = new FormData(); form.append("k1", "v1"); form.append("fff", fileObj); $.ajax({ type:'POST', url: '/index', data: form, processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType success: function(arg){ console.log(arg); } }) } </script> </body>
<body> <form id="my_form" name="form" action="/index" method="POST" enctype="multipart/form-data" > <div id="main"> <input name="fff" id="my_file" type="file" /> <input type="button" name="action" value="Upload" onclick="redirect()"/> <iframe id='my_iframe' name='my_iframe' src="" class="hide"></iframe> </div> </form> <script> function redirect(){ document.getElementById('my_iframe').onload = Testt; document.getElementById('my_form').target = 'my_iframe'; document.getElementById('my_form').submit(); } function Testt(ths){ var t = $("#my_iframe").contents().find("body").text(); console.log(t); } </script> </body>
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') def post(self, *args, **kwargs): file_metas = self.request.files["fff"] # print(file_metas) for meta in file_metas: file_name = meta['filename'] with open(file_name,'wb') as up: up.write(meta['body']) settings = { 'template_path': 'template', } application = tornado.web.Application([ (r"/index", MainHandler), ], **settings) if __name__ == "__main__": application.listen(8000) tornado.ioloop.IOLoop.instance().start()
<script type="text/javascript"> $(document).ready(function () { $("#formsubmit").click(function () { var iframe = $('<iframe name="postiframe" id="postiframe" style="display: none"></iframe>'); $("body").append(iframe); var form = $('#theuploadform'); form.attr("action", "/upload.aspx"); form.attr("method", "post"); form.attr("encoding", "multipart/form-data"); form.attr("enctype", "multipart/form-data"); form.attr("target", "postiframe"); form.attr("file", $('#userfile').val()); form.submit(); $("#postiframe").load(function () { iframeContents = this.contentWindow.document.body.innerHTML; $("#textarea").html(iframeContents); }); return false; }); }); </script> <form id="theuploadform"> <input id="userfile" name="userfile" size="50" type="file" /> <input id="formsubmit" type="submit" value="Send File" /> </form> <div id="textarea"> </div>
$('#upload_iframe').load(function(){ var iframeContents = this.contentWindow.document.body.innerText; iframeContents = JSON.parse(iframeContents); })
function bindChangeAvatar1() { $('#avatarImg').change(function () { var file_obj = $(this)[0].files[0]; $('#prevViewImg')[0].src = window.URL.createObjectURL(file_obj) }) } function bindChangeAvatar2() { $('#avatarImg').change(function () { var file_obj = $(this)[0].files[0]; var reader = new FileReader(); reader.readAsDataURL(file_obj); reader.onload = function (e) { $('#previewImg')[0].src = this.result; }; }) } function bindChangeAvatar3() { $('#avatarImg').change(function () { var file_obj = $(this)[0].files[0]; var form = new FormData(); form.add('img_upload', file_obj); $.ajax({ url: '', data: form, processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType success: function (arg) { } }) }) } function bindChangeAvatar4() { $('#avatarImg').change(function () { $(this).parent().submit(); $('#upload_iframe').load(function () { var iframeContents = this.contentWindow.document.body.innerText; iframeContents = JSON.parse(iframeContents); if (iframeContents.status) { $('#previewImg').attr('src', '/' + iframeContents.data); } }) }) } 其餘
一、基本使用
首先,先看一段代碼
class AsyncHandler(tornado.web.RequestHandler): def get(self): import time time.sleep(20) self.write('666') application = tornado.web.Application([ (r"/index", MainHandler), (r"/async", AsyncHandler), ], **settings)
對於異步非阻塞的瞭解,第一點確定是, 單線程;因此測試一下上面的代碼,不難發現:先打開async頁面,沒有任何返回,一直顯示在加載,此時打開index,發現index頁面同時也在加載出不來。
當async執行完,index頁面也很快就返回了。
此時修改一下代碼:
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web from tornado.web import UIModule from tornado import gen from tornado.concurrent import Future import time class MainHandler(tornado.web.RequestHandler): def get(self): self.render("index.html", list_info=[11, 22, 33], key1='value1') class AsyncHandler(tornado.web.RequestHandler): @gen.coroutine def get(self): future = Future() tornado.ioloop.IOLoop.current().add_timeout(time.time() + 20, self.doing) yield future def doing(self, *args, **kwargs): self.write('async') self.finish() settings = { 'template_path': 'tmp', 'static_path': 'statics' } application = tornado.web.Application([ (r"/index", MainHandler), (r"/async", AsyncHandler), ], **settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
此時再執行上面的操做,就會發現當async阻塞等待返回的時候,其餘網頁是能夠繼續訪問的。這樣單位時間處理的請求也就更多了。在服務器端將單線程用到極致。
裝飾器 + Future 從而實現Tornado的異步非阻塞,異步非阻塞的核心其實就在這個Future上,這個future類有點相似於一個標記,當裝飾器裝飾函數,函數內部實例化Future,並添加回調函數後。執行代碼:
from tornado import gen from tornado.concurrent import Future 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()
發現請求一直沒有返回。實際上實例化future以後,產生了一個flag,只有當準備好響應數據或者知足響應條件的時候才能夠回調callback函數,返回給客戶端。
二、同步阻塞與異步非阻塞對比
前面的第一個實例其實就是同步阻塞的實例了。
class SyncHandler(tornado.web.RequestHandler): def get(self): self.doing() self.write('sync') def doing(self): time.sleep(10)
class AsyncHandler(tornado.web.RequestHandler): @gen.coroutine def get(self): future = Future() tornado.ioloop.IOLoop.current().add_timeout(time.time() + 5, self.doing) yield future def doing(self, *args, **kwargs): self.write('async') self.finish()
三、httpclient類庫
Tornado提供了httpclient類庫用於發送Http請求,能夠配合異步非阻塞使用。
import tornado.web from tornado import gen from tornado import httpclient # 方式一: class AsyncHandler(tornado.web.RequestHandler): @gen.coroutine def get(self, *args, **kwargs): print('進入') http = httpclient.AsyncHTTPClient() data = yield http.fetch("http://www.google.com") print('K.O.',data) self.finish('6666') # 方式二: # class AsyncHandler(tornado.web.RequestHandler): # @gen.coroutine # def get(self): # print('進入') # http = httpclient.AsyncHTTPClient() # yield http.fetch("http://www.google.com", self.done) # # def done(self, response): # print('K.O.') # self.finish('666') application = tornado.web.Application([ (r"/async", AsyncHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
說到這,咱們來測試下經過另外一個url來改變future的標記位。
補充:
import tornado.ioloop import tornado.web from tornado.web import UIModule from tornado import gen from tornado.concurrent import Future future = None class MainHandler(tornado.web.RequestHandler): def get(self): self.render("index.html", list_info=[11, 22, 33], key1='value1') class AsyncHandler(tornado.web.RequestHandler): @gen.coroutine def get(self): global future 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() class StopHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): future.set_result('...') settings = { 'template_path': 'tmp', 'static_path': 'statics' } application = tornado.web.Application([ (r"/index", MainHandler), (r"/async", AsyncHandler), (r"/stop", StopHandler), ], **settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
200行的自定義異步非阻塞web框架
#!/usr/bin/env python3 # encoding: utf-8 # Author: Dandy import re import socket import select import time class HttpResponse(object): """ 封裝響應信息 """ def __init__(self, content=''): self.content = content self.headers = {} self.cookies = {} def response(self): return bytes(self.content, encoding='utf-8') class HttpNotFound(HttpResponse): """ 404時的錯誤提示 """ def __init__(self): super(HttpNotFound, self).__init__('404 Not Found') class HttpRequest(object): """ 用戶封裝用戶請求信息 """ def __init__(self, conn): self.conn = conn self.header_bytes = bytes() self.header_dict = {} self.body_bytes = bytes() self.method = "" self.url = "" self.protocol = "" self.initialize() self.initialize_headers() def initialize(self): header_flag = False while True: try: received = self.conn.recv(8096) except Exception as e: received = None if not received: break if header_flag: self.body_bytes += received continue temp = received.split(b'\r\n\r\n', 1) if len(temp) == 1: self.header_bytes += temp else: h, b = temp self.header_bytes += h self.body_bytes += b header_flag = True @property def header_str(self): return str(self.header_bytes, encoding='utf-8') def initialize_headers(self): headers = self.header_str.split('\r\n') first_line = headers[0].split(' ') if len(first_line) == 3: self.method, self.url, self.protocol = headers[0].split(' ') for line in headers: kv = line.split(':') if len(kv) == 2: k, v = kv self.header_dict[k] = v class Future(object): """ 異步非阻塞模式時封裝回調函數以及是否準備就緒 """ def __init__(self, callback): self.callback = callback self._ready = False self.value = None def set_result(self, value=None): self.value = value self._ready = True @property def ready(self): return self._ready class TimeoutFuture(Future): """ 異步非阻塞超時 """ def __init__(self, timeout): super(TimeoutFuture, self).__init__(callback=None) self.timeout = timeout self.start_time = time.time() @property def ready(self): current_time = time.time() if current_time > self.start_time + self.timeout: self._ready = True return self._ready class Snow(object): """ 微型Web框架類 """ def __init__(self, routes): self.routes = routes self.inputs = set() self.request = None self.async_request_handler = {} def run(self, host='localhost', port=9999): """ 事件循環 :param host: :param port: :return: """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((host, port,)) sock.setblocking(False) # 非阻塞 sock.listen(128) sock.setblocking(0) self.inputs.add(sock) # 將此socket添加到inputs這個集合裏 try: while True: readable_list, writeable_list, error_list = select.select(self.inputs, [], self.inputs,0.005) # 監聽 for conn in readable_list: # 循環可讀的集合 if sock == conn: # socket有新的鏈接進來 client, address = conn.accept() # 獲取conn、addr client.setblocking(False) self.inputs.add(client) # 將此鏈接conn加入監聽 else: gen = self.process(conn) # 獲取、處理鏈接conn,拿請求體請求體 if isinstance(gen, HttpResponse): # 若是返回的是HttpResponse類型的,表明是正常的請求 conn.sendall(gen.response()) # 發送給客戶端 self.inputs.remove(conn) # 既然返回了,則須要從監聽隊列移除 conn.close() # 關閉此socket鏈接 else: yielded = next(gen) # 不是正常的請求就一定是yield future self.async_request_handler[conn] = yielded # future對象加入字典中key==》conn,value==》future對象 self.polling_callback() # for 循環執行完,執行此函數 except Exception as e: pass finally: sock.close() def polling_callback(self): """ 遍歷觸發異步非阻塞的回調函數 :return: """ for conn in list(self.async_request_handler.keys()): # 循環取key yielded = self.async_request_handler[conn] # 根據循環的key取value # conn:socket對象 # yielded:future對象 if not yielded.ready: # ready是布爾值,若是執行了set_result,就變成true,表示已經就緒 continue # 不然循環繼續 if yielded.callback: # 若是被set result ret = yielded.callback(self.request, yielded) conn.sendall(ret.response()) # 發送數據 self.inputs.remove(conn) # 從監聽內移除此conn del self.async_request_handler[conn] # 從循環字典刪除 conn.close() # 關閉conn def process(self, conn): """ 處理路由系統以及執行函數 :param conn: :return: """ self.request = HttpRequest(conn) func = None for route in self.routes: if re.match(route[0], self.request.url): func = route[1] break if not func: return HttpNotFound() else: return func(self.request)
使用
from snow import Snow from snow import HttpResponse def index(request): return HttpResponse('OK') routes = [ (r'/index/', index), ] app = Snow(routes) app.run(port=8012)
from snow import Snow from snow import HttpResponse from snow import TimeoutFuture request_list = [] def async(request): obj = TimeoutFuture(5) yield obj def home(request): return HttpResponse('home') routes = [ (r'/home/', home), (r'/async/', async), ] app = Snow(routes) app.run(port=8012)
from snow import Snow from snow import HttpResponse from snow import Future request_list = [] def callback(request, future): return HttpResponse(future.value) def req(request): obj = Future(callback=callback) request_list.append(obj) yield obj def stop(request): obj = request_list[0] del request_list[0] obj.set_result('done') return HttpResponse('stop') routes = [ (r'/req/', req), (r'/stop/', stop), ] app = Snow(routes) app.run(port=8012)
基於等待模式能夠完成自定製操做
本blog參考自:https://www.cnblogs.com/wupeiqi/p/6536518.html