Tornado 是 FriendFeed 使用的可擴展的非阻塞式 web 服務器及其相關工具的開源版本。這個 Web 框架看起來有些像web.py 或者 Google 的 webapp,不過爲了能有效利用非阻塞式服務器環境,這個 Web 框架還包含了一些相關的有用工具 和優化。javascript
Tornado 和如今的主流 Web 服務器框架(包括大多數 Python 的框架)有着明顯的區別:它是非阻塞式服務器,並且速度至關快。得利於其 非阻塞的方式和對 epoll 的運用,Tornado 每秒能夠處理數以千計的鏈接,這意味着對於實時 Web 服務來講,Tornado 是一個理想的 Web 框架。咱們開發這個 Web 服務器的主要目的就是爲了處理 FriendFeed 的實時功能 ——在 FriendFeed 的應用裏每個活動用戶都會保持着一個服務器鏈接。(關於如何擴容 服務器,以處理數以千計的客戶端的鏈接的問題,請參閱 C10K problem。)css
下載安裝:html
pip3 install tornado 源碼安裝 https://pypi.python.org/packages/source/t/tornado/tornado-4.3.tar.gz
1、快速上手前端
#!/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") application = tornado.web.Application([ (r"/index", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
執行過程:java
第一步:執行腳本,監聽 8888 端口python
第二步:瀏覽器客戶端訪問 /index --> http://127.0.0.1:8888/indexjquery
第三步:服務器接受請求,並交由對應的類處理該請求git
第四步:類接受到請求以後,根據請求方式(post / get / delete ...)的不一樣調用並執行相應的方法github
第五步:方法返回值的字符串內容發送瀏覽器web
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web from tornado import httpclient from tornado.web import asynchronous from tornado import gen import uimodules as md import uimethods as mt class MainHandler(tornado.web.RequestHandler): @asynchronous @gen.coroutine def get(self): print 'start get ' http = httpclient.AsyncHTTPClient() http.fetch("http://127.0.0.1:8008/post/", self.callback) self.write('end') def callback(self, response): print response.body settings = { 'template_path': 'template', 'static_path': 'static', 'static_url_prefix': '/static/', 'ui_methods': mt, 'ui_modules': md, } application = tornado.web.Application([ (r"/index", MainHandler), ], **settings) if __name__ == "__main__": application.listen(8009) tornado.ioloop.IOLoop.instance().start()
注意: self.render('xx.html') 等, 仍然會執行完後面的語句再加載頁面
2、路由系統
路由系統其實就是 url 和 類 的對應關係,這裏不一樣於其餘框架。
其餘不少框架均是 url 對應函數,Tornado中每一個url對應的是一個類。
#!/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") class StoryHandler(tornado.web.RequestHandler): def get(self, story_id): self.write("You requested the story " + story_id) class BuyHandler(tornado.web.RequestHandler): def get(self): self.write("buy.wupeiqi.com/index") application = tornado.web.Application([ (r"/index", MainHandler), (r"/story/([0-9]+)", StoryHandler), ]) application.add_handlers('buy.5poi.com$', [ (r'/index',BuyHandler), ]) if __name__ == "__main__": application.listen(80) tornado.ioloop.IOLoop.instance().start()
Tornado中原生支持二級域名的路由,如:
application = tornado.web.Application([ (r"/index", MainHandler), ]) application.add_handlers('buy.5poi.com$', [ (r'/index',BuyHandler), ])
3、模板引擎
Tornao中的模板語言和django中相似,模板引擎將模板文件載入內存,而後將數據嵌入其中,最終獲取到一個完整的字符串,再將字符串返回給請求者。
Tornado 的模板支持「控制語句」和「表達語句」。
控制語句是使用 {%
和 %}
包起來的 例如 {% if len(items) > 2 %}
表達語句是使用 {{
和 }}
包起來的,例如 {{ items[0] }}
控制語句和對應的 Python 語句的格式基本徹底相同。
咱們支持 if
、for
、while
和 try
,這些語句邏輯結束的位置須要用 {% end %}
作標記。
還經過 extends
和 block
語句實現了模板繼承。這些在 template
模塊 的代碼文檔中有着詳細的描述。
注:在使用模板前須要在setting中設置模板路徑:"template_path" : "views相應的文件夾"
一、基本使用
#!/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()
<!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 的別名
二、母版 extends 經常使用於頁面總體佈局
{% extends 'layout.html'%} 引入layout.html {% block body1 %} body1 替換到 layout.html 中的body1 <h1>Index</h1> {% end %}
<!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 %}
三、導入 include 經常使用於導入小組件
<div> <ul> <li>1024</li> <li>42區</li> </ul> </div>
<!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> <script src="{{static_url("js/jquery-1.8.2.min.js")}}"></script> </body> </html>
四、自定義UIMethod以UIModule
a. 定義
# uimethods.py def tab(self): return 'UIMethod'
#!/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 '<h1>alex</h1>' #return escape.xhtml_escape('<h1>alex</h1>')
b. 註冊
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web from tornado.escape import linkify import uimodules as md import uimethods as mt class MainHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') settings = { 'template_path': 'template', 'static_path': 'static', 'static_url_prefix': '/static/', 'ui_methods': mt, 'ui_modules': md, } application = tornado.web.Application([ (r"/index", MainHandler), ], **settings) if __name__ == "__main__": application.listen(8009) tornado.ioloop.IOLoop.instance().start()
c. 使用
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <link href="{{static_url("commons.css")}}" rel="stylesheet" /> </head> <body> <h1>hello</h1> {% module custom(123) %} {{ tab() }} </body>
4、靜態文件
對於靜態文件,能夠配置靜態文件的目錄和前端使用時的前綴,而且Tornaodo還支持靜態文件緩存。
#!/usr/bin/env python # -*- coding:utf-8 -*- import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.render('home/index.html') settings = { 'template_path': 'template', 'static_path': 'static', 'static_url_prefix': '/static/', } application = tornado.web.Application([ (r"/index", MainHandler), ], **settings) if __name__ == "__main__": application.listen(80) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <link href="{{static_url("commons.css")}}" rel="stylesheet" /> </head> <body> <h1>hello</h1> </body> </html>
注:靜態文件緩存的實現
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()
注意: 想要靜態文件自定義處理,不經過 static_url('xxx') 訪問:
application = tornado.web.Application([ (r"/(upload/.*.jpg)", tornado.web.StaticFileHandler, dict(path=settings['static_path'])), ],**settings)
5、cookie
Tornado中能夠對cookie進行操做,而且還能夠對cookie進行簽名以防止僞造。
self.set_cookie(self, name, value, domain=None, expires=None, path="/", expires_days=None, **kwargs)
name |
Cookie的Key |
value |
Cookie的value |
domain |
生效的域名 |
expires |
以秒爲過時時間,默認從 1970-01-01T00:00:10.000Z |
path |
生效路徑 |
expires_days |
以天數過時時間,若是設置爲 None 則關閉瀏覽器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就失效, 設置 expires_days=None 注意的是不要同時傳遞expires 和 expires_days self.set_cookie('user_id', '1', expires_days=None, expires=某個時間) expires_day=None, 或者expires_day=3, 即3天, 都不會影響expires的, 由於expires比expires_days 的優先級高 self.set_cookie('user_id', '1', expires=time.time()+15*60) 15分鐘過時 path='/' 表示全局 self.set_cookie('user_id', '1', path='/',expires=time.time()+15*60)
二、加密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!") setting = { 'cookie_secret':'58ksjfSmxoi' } application = tornado.web.Application([ (r"/", MainHandler), ],**setting)
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的實現機制相同。
import tornado.web import tornado.ioloop class IndexHandler(tornado.web.RequestHandler): def get(self): self.set_secure_cookie('username', 'ansheng') self.set_secure_cookie('password', 'hello') self.render('index.html') def post(self, *args, **kwargs): username = self.get_argument('username', None) password = self.get_argument('password', None) cooike_user = str(self.get_secure_cookie('username'), encoding='utf-8') cooike_pass = str(self.get_secure_cookie('password'), encoding='utf-8') if username == cooike_user and password == cooike_pass: self.write('Hello ' + cooike_user) else: self.write('用戶名或密碼錯誤') settings = { 'template_path': 'template', } application = tornado.web.Application([ (r'/', IndexHandler), ], **settings, cookie_secret="508C934B83CC") if __name__ == '__main__': application.listen(8000) 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中也有指定的插件 jQuery Cookie 專門用於操做cookie,猛擊這裏
6、CSRF
Tornado中的跨站請求僞造和Django中的類似,跨站僞造請求(Cross-site request forgery)
1.設置:
settings = { "xsrf_cookies": True, }
頁面加載後,cookie裏有一個爲 _xsrf = 'xxxxxxxxxxxx' 的值.
須要傳遞_xsrf的值請求才能經過.
2.form 表單:
<form action="/index" method="post"> {% raw xsrf_form_html() %} <input type="text" name="message"/> <input type="submit" value="Post"/> </form>
3.ajax
<!-- 一個獲取cookie的方法 !--> function getCookie(name) { var r = document.cookie.match("\\b" + name + "=([^;]*)\\b"); return r ? r[1] : undefined; } <!-- ajax提交數據中,寫上獲取的cookie值 !--> var cookie= getCookie("_xsrf"); $.post({ url:'/index', data:{'content':'v1', '_xsrf' :cookie}, success:function (callbakc) { console.log(callbakc) } });
注:Ajax使用時,本質上就是去獲取本地的cookie,攜帶cookie再來發送請求
7、上傳文件
上傳文件標籤: <input type="file" name="file" id="my_file" />
後臺獲取: file_metas = self.request.files['file']
獲取格式: [{'body': b'xxxxxxxxx', 'content_type': 'text/plain', 'filename': '文件名.txt/...'},...多個文件]
一、Form表單上傳
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>上傳文件</title> </head> <body> <form id="my_form" name="form" action="/index" method="POST" enctype="multipart/form-data" > <input name="fff" id="my_file" type="file" /> <input type="submit" value="提交" /> </form> </body> </html>
#!/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') 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()
二、AJAX上傳
1.基於XMLHttpRequest
<input type="file" id="img" /> <input type="button" onclick="UploadFile();" /> <script> function UploadFile(){ var fileObj = document.getElementById("img")[0].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>
2.基於Jquery
function UploadFile() { var fileObj = $("#file1")[0].files[0]; var form = new FormData(); form.append("k1", "v1"); form.append("fff", fileObj); $.ajax({ type:'post', url:'/upload', data:form, processData: false, // tell jQuery not to process the data contentType: false, // tell jQuery not to set contentType }); }
3.基於iframe
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <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> </html>
<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>
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);
}
})
})
}
8、驗證碼
驗證碼原理在於後臺自動建立一張帶有隨機內容的圖片,而後將內容經過img標籤輸出到頁面。
安裝圖像處理模塊:
pip3 install pillow
示例截圖:
驗證碼Demo源碼下載:猛擊這裏
class CheckcodeHandler(BaseHandler): def get(self, *args, **kwargs): import io import check_code mstream = io.BytesIO() img, code = check_code.create_validate_code() self.session['code'] = code //生成驗證碼存放在session中 img.save(mstream, "GIF") self.write(mstream.getvalue()) ************************************************ <p> <input name='code' type="text" placeholder="驗證碼" /> <img src="/check_code" onclick='ChangeCode();' id='imgCode'> </p> <script type="text/javascript"> function ChangeCode() { var code = document.getElementById('imgCode'); code.src += '?'; //點擊一次圖片,換一次激活碼 } </script>
9、異步非阻塞
一、基本使用
裝飾器 + 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對象中放置數據或信號時,此鏈接是不斷開的。
二、同步阻塞和異步非阻塞對比
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請求,其配合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()
1、Session
一、面向對象基礎
面向對象中經過索引的方式訪問對象,須要內部實現 __getitem__ 、__delitem__、__setitem__方法
#!/usr/bin/env python # -*- coding:utf-8 -*- class Foo(object): def __getitem__(self, key): print '__getitem__',key def __setitem__(self, key, value): print '__setitem__',key,value def __delitem__(self, key): print '__delitem__',key obj = Foo() result = obj['k1'] #obj['k2'] = 'alex' #del obj['k1']
二、Tornado擴展
Tornado框架中,默認執行Handler的get/post等方法以前默認會執行 initialize方法,因此能夠經過自定義的方式使得全部請求在處理前執行操做...
class BaseHandler(tornado.web.RequestHandler): def initialize(self): self.xxoo = "alex" class MainHandler(BaseHandler): def get(self): print(self.xxoo) self.write('index') class IndexHandler(BaseHandler): def get(self): print(self.xxoo) self.write('index')
三、session
session其實就是定義在服務器端用於保存用戶回話的容器,其必須依賴cookie才能實現。
#!/usr/bin/env python # -*-coding:utf-8 -*- import tornado.ioloop import tornado.web container = {} class Session(): def __init__(self,handler): self.handler = handler self.random_str = None def get_random_str(self): import hashlib import time hash = hashlib.md5() hash.update(bytes(str(time.time()), encoding='utf-8')) random_str = hash.hexdigest() return random_str def __setitem__(self, key, value): if not self.random_str: random_str = self.handler.get_cookie('_session', None) if not random_str: random_str = self.get_random_str() container[random_str] = {} else: if random_str not in container.keys(): random_str = self.get_random_str() container[random_str] = {} self.random_str = random_str container[self.random_str][key] = value self.handler.set_cookie('_session', self.random_str) def __getitem__(self, key): random_str = self.handler.get_cookie('_session', None) if not random_str: return None user_info_dict = container.get(random_str, None) if not user_info_dict: return None value = user_info_dict.get(key,None) return value class BaseHandler(tornado.web.RequestHandler): def initialize(self): self.session = Session(self) class MainHandler(BaseHandler): def get(self): print(self.cookies) self.session['kkk'] = '123' self.write("Hello, world") application = tornado.web.Application([ (r"/index", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
2、表單驗證
在Web程序中每每包含大量的表單驗證的工做,如:判斷輸入是否爲空,是否符合規則。
例子1:
import tornado.ioloop import tornado.web from hashlib import sha1 import os, time import re class MainForm(object): def __init__(self): self.host = "(.*)" self.ip = "^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$" self.port = '(\d+)' self.phone = '^1[3|4|5|8][0-9]\d{8}$' def check_value(self,handler): flag = True input_dict = {} for key,regular in self.__dict__.items(): input_value = handler.get_argument(key) val = re.match(regular,input_value) if not val: flag = False input_dict[key] = input_value print(val,input_dict[key],regular) return flag,input_dict class MainHandler(tornado.web.RequestHandler): def get(self): self.render("index.html") def post(self, *args, **kwargs): obj = MainForm() val,input_dict = obj.check_value(self) print(val,input_dict) settings = { 'template_path': 'views', # 模版路徑的配置 'static_path' : 'static', # 靜態文件路徑 # 'static_url_prefix' : '/sss/', } application = tornado.web.Application([ (r"/index", MainHandler), ],**settings) if __name__ == "__main__": application.listen(8889) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <h1>hello</h1> <form action="/index" method="post"> <p>hostname: <input type="text" name="host" placeholder="host"/> </p> <p>ip: <input type="text" name="ip" placeholder="ip"/> </p> <p>port: <input type="text" name="port" placeholder="port" /> </p> <p>phone: <input type="text" name="phone" placeholder="phone"/> </p> <input type="submit" /> </form> </body> </html>
例子2:
import tornado.ioloop import tornado.web from hashlib import sha1 import os, time import re class IPField(): REGULAR = "^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$" def __init__(self,required=True,error_dict=None): self.error_dict = {} #錯誤信息 if error_dict: self.error_dict.update(error_dict) #用戶自定錯誤信息 self.required = required self.value = None self.error = None self.is_valid = False def validate(self,name,input_value): if not self.required: # 能夠爲空 self.value = input_value self.is_valid = True else: #1.不能爲空,用戶輸入爲空 #2.用戶輸入錯誤, #3.用戶輸入正確 if not input_value: if self.error_dict.get('required',None): self.error = self.error_dict['required'] else: self.error = '%s is requires '%(name) else: val = re.match(IPField.REGULAR,input_value) if not val: #用戶輸入錯誤 , re返回None if self.error_dict.get('valid', None): self.error = self.error_dict['valid'] else: self.error = '%s is valid ' % (name) else: self.value = input_value self.is_valid = True class CheckBoxField(): def __init__(self,required=True,error_dict=None): self.error_dict = {} if error_dict: self.error_dict.update(error_dict) self.required = required self.value = None self.error = None self.is_valid = False def validate(self,name,input_value): if not self.required: self.value = input_value self.is_valid = True else: if not input_value: if self.error_dict.get('required',None): self.error = self.error_dict['required'] else: self.error = '%s is requires '%(name) else: self.value = input_value self.is_valid = True class FileField(): REGULAR = "^(\w+\.pdf)|(\w+\.mp3)|(\w+\.py)$" def __init__(self, required=True, error_dict=None): self.error_dict = {} if error_dict: self.error_dict.update(error_dict) self.required = required self.value = [] self.error = None self.is_valid = True self.success_file_name_list = [] self.name = None def validate(self, name, all_file_name_list): self.name = name if not self.required: self.value = all_file_name_list else: if not all_file_name_list: self.is_valid = False if self.error_dict.get('required', None): self.error = self.error_dict['required'] else: self.error = '%s is requires ' % (name) else: for file_name in all_file_name_list: val = re.match(FileField.REGULAR, file_name) if not val: self.is_valid = False if self.error_dict.get('valid', None): self.error = self.error_dict['valid'] else: self.error = '%s is valid ' % (name) break else: self.value.append(file_name) def save(self,handler,path='upload'): file_list = handler.request.files.get(self.name) for file in file_list: file_name = file['filename'] file_path = os.path.join(path,file_name) if file_name and file_name in self.value: with open(file_path,'wb') as up: up.write(file['body']) class BaseForm(): def check_value(self,handler): flag = True success_value_dict = {} error_message_dict = {} for key,regular in self.__dict__.items(): if type(regular) == CheckBoxField: input_value = handler.get_arguments(key) # checkbox取值 elif type(regular) == FileField: file_list = handler.request.files.get(key,[]) # 文件對象 input_value = [] for item in file_list: input_value.append(item['filename']) else: input_value = handler.get_argument(key) regular.validate(key,input_value) if regular.is_valid: success_value_dict[key] = regular.value else: flag=False error_message_dict[key] = regular.error return flag,success_value_dict,error_message_dict class HomeForm(BaseForm): def __init__(self): self.ip = IPField(required=True,error_dict={'required':'ip 不能爲空!' , 'valid':'格式錯誤!!'}) self.aihao = CheckBoxField(required=False,error_dict={'required':'checkbox 不能爲空!' , 'valid':'格式錯誤!!'}) self.fafafa = FileField(required=True) class HomeHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): self.render('home.html',error_message = None) def post(self, *args, **kwargs): obj = HomeForm() val, success_value_dict , error_message_dict = obj.check_value(self) print(val, success_value_dict , error_message_dict) if val : #全部驗證經過 文件上傳 obj.fafafa.save(self) self.render('home.html',error_message = None) settings = { 'template_path': 'views', # 模版路徑的配置 'static_path' : 'static', # 靜態文件路徑 # 'static_url_prefix' : '/sss/', } application = tornado.web.Application([ (r"/home", HomeHandler), ],**settings) if __name__ == "__main__": application.listen(8889) tornado.ioloop.IOLoop.instance().start()
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <h1>hello</h1> <form action="/home" method="post" enctype="multipart/form-data"> <p>ip: <input type="text" name="ip" placeholder="ip"/> </p> <input type="checkbox" name='aihao' value="1">籃球 <input type="checkbox" name='aihao' value="2">足球 <input type="checkbox" name='aihao' value="3">乒乓球 <input type="file" name="fafafa"> <input type="file" name="fafafa"> {% if error_message %} <span style="color: red">{{ error_message['ip'] }}</span> {% end %} <input type="submit" /> </form> </body> </html>
3、分頁
核心: 後端生成標籤,返回給前端顯示。
效果:
首頁 上一頁 1 2 3 4 5 6 7 8 9 10 11 下一頁 尾頁
首頁 上一頁 2 3 4 5 6 7 8 9 10 11 12 下一頁 尾頁
首頁 上一頁 2 3 4 5 6 7 8 9 10 11 12 下一頁 尾頁
設計思路:
1.當總頁數 all_page 小於11時,
=> 是,( 直接生成所有頁碼 ) 設置 起始頁s = 1 , 結束頁t = all_page
=> 否,噹噹前頁current_page 小於6時,(頁碼不發生改變)
=> 是, s = 1 , t = 11
=> 否, 當current_page + 5 < all_page 時,
=> 是 , s = current_page - 5 , t = current_page + 5
=> 否 , ( 此時當前頁爲最後5頁 ,再也不日後生成頁碼 ,保持原來不變) s = all_page - 10 , t = all_page
2.當前頁爲1時,點擊上一頁,首頁不跳轉,當前頁爲最後一頁時,點擊下一頁,尾頁不跳轉。href='javascript:void(0)'
3.字典存儲生成的a標籤, join()鏈接列表每項,生成字符串標籤返回前端
4.前端顯示,輸出原始標籤字符串 {%raw str_page %}
def page_str(self,base_url): if self.all_page < 11: s = 1 t = self.all_page else: if self.current_page < 6: s = 1 t = 11 else: if (self.current_page + 5) < self.all_page: s = self.current_page - 5 t = self.current_page + 5 else: s = self.all_page - 10 t = self.all_page list_page = [] # 首頁 first_page = "<a href='%s1'>首頁</a>" % (base_url) list_page.append(first_page) # 上一頁 if self.current_page == 1: pre_page = "<a href='javascript:void(0)'>上一頁</a>" else: pre_page = "<a href='%s%s'>上一頁</a>" % (base_url, self.current_page -1 ,) list_page.append(pre_page) # 頁碼生成 for i in range(s, t + 1): if i == self.current_page: temp = "<a class='active-paper' href='%s%s'>%s</a>" % (base_url,i, i) else: temp = "<a href='%s%s'>%s</a>" % (base_url , i, i) list_page.append(temp) # 下一頁 if self.current_page >= self.all_page: next_page = "<a href='javascript:void(0)'>下一頁</a>" else: next_page = "<a href='%s%s'>下一頁</a>" % (base_url, self.current_page + 1,) list_page.append(next_page) # 尾頁 end_page = "<a href='%s%s'>尾頁</a>" % (base_url,self.all_page) list_page.append(end_page) # 頁面跳轉 pagejump_input = """<input type="text"><a onclick="pageNumjump(this,'%s')">Go</a>"""%(base_url) pagejump_script = """ <script> function pageNumjump(ths,base_url){ var pagenum = ths.previousElementSibling.value; if (pagenum.trim().length > 0){ location.href = base_url+pagenum } } </script> """ list_page.append(pagejump_input) list_page.append(pagejump_script) # 數據拼接 返回 str_page = ''.join(list_page) # 列表鏈接成爲字符串 return str_page
仿:chouti.com分頁顯示:
上一頁 1 ... 4 5 6 7 8 9 10 下一頁
def page_str(self,base_url): if self.all_page < 10: s = 1 t = self.all_page else: if self.current_page < 7: s = 1 t = 10 else: if self.all_page - self.current_page >= 4 : s = self.current_page - 3 t = self.current_page + 4 else: s = self.all_page - 6 t = self.all_page list_page = [] # 上一頁 if self.current_page != 1: pre_page = "<a href='%s%s' class='pageedg'>上一頁</a>" % (base_url, self.current_page - 1,) list_page.append(pre_page) # 頁碼生成 # 生成 1 , ... , if( self.current_page >= 7 ): temp = "<a class='pageNum' href='%s%s'>%s</a>" % (base_url, 1, 1) list_page.append(temp) temp = "<span class='ignore' >...</span>" list_page.append(temp) for i in range(s, t + 1): if i == self.current_page: temp = "<span class='active-page' href='%s%s'>%s</span>" % (base_url,i, i) else: temp = "<a href='%s%s' class='pageNum'>%s</a>" % (base_url , i, i) list_page.append(temp) # 下一頁 if self.current_page < self.all_page: next_page = "<a href='%s%s' class='pageedg'>下一頁</a>" % (base_url, self.current_page + 1,) list_page.append(next_page) str_page = ''.join(list_page) # 列表鏈接成爲字符串 return str_page