Tornado 是 FriendFeed 使用的可擴展的非阻塞式 web 服務器及其相關工具的開源版本。這個 Web 框架看起來有些像web.py 或者 Google 的 webapp,不過爲了能有效利用非阻塞式服務器環境,這個 Web 框架還包含了一些相關有用工具及優化。javascript
Tornado 和如今的主流 Web 服務器框架(包括大多數 Python 的框架)有着明顯的區別:它是非阻塞式服務器,並且速度至關快。得利於其非阻塞的方式和對 epoll 的運用,Tornado 每秒能夠處理數以千計的鏈接,這就意味着對於實時的 Web 服務來講,Tornado 是一個理想的 Web 框架。開發這個 Web 服務器的主要目的就是爲了處理 FriendFeed 的實時功能 ——在 FriendFeed 的應用裏每個活動用戶都會保持着一個服務器鏈接。(關於如何擴容服務器,以處理數以千計的客戶端的鏈接的問題,請參閱 C10K problem。)css
請參見 Tornado 文檔 或 Tornado 原文文檔(鏡像)以詳細瞭解該 Web 框架。html
pip安裝 pip3 install tornado 源碼安裝 tar xvzf tornado-4.4.1.tar.gz cd tornado-4.4.1 python setup.py build sudo python setup.py install
源碼下載:tornado-1.2.1.tar.gz、 tornado-4.4.1.tar.gz java
主要模塊 web - FriendFeed 使用的基礎 Web 框架,包含了 Tornado 的大多數重要的功能 escape - XHTML, JSON, URL 的編碼/解碼方法 database - 對 MySQLdb 的簡單封裝,使其更容易使用 template - 基於 Python 的 web 模板系統 httpclient - 非阻塞式 HTTP 客戶端,它被設計用來和 web 及 httpserver 協同工做 auth - 第三方認證的實現(包括 Google OpenID/OAuth、Facebook Platform、Yahoo BBAuth、FriendFeed OpenID/OAuth、Twitter OAuth) locale - 針對本地化和翻譯的支持 options - 命令行和配置文件解析工具,針對服務器環境作了優化 底層模塊 httpserver - 服務於 web 模塊的一個很是簡單的 HTTP 服務器的實現 iostream - 對非阻塞式的 socket 的簡單封裝,以方便經常使用讀寫操做 ioloop - 核心的 I/O 循環 Tornado 各模塊
"Hello, world" 及 Application settings 基本配置:python
import tornado.ioloop import tornado.web # import uimodules as md # import uimethods as mt class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") settings = { 'template_path': 'views', # html文件 'static_path': 'statics', # 靜態文件(css,js,img) 'static_url_prefix': '/statics/',# 靜態文件前綴 'cookie_secret': 'suoning', # cookie自定義字符串加鹽 # 'xsrf_cookies': True, # 防止跨站僞造 # 'ui_methods': mt, # 自定義UIMethod函數 # 'ui_modules': md, # 自定義UIModule類 } application = tornado.web.Application([ (r"/", MainHandler), ], **settings) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
請求來時,程序會用正則匹配相應路由地址,並交付於 tornado.web.RequestHandler 的子類處理;子類會根據請求方式(post / get / delete ...)的不一樣調用並執行相應的方法,方法返回字符串內容併發送到瀏覽器。jquery
self.write("<h1>Hello, World</h1>") # html代碼直接寫在瀏覽器客戶端 self.render("index.html") # 返回html文件,調用render_string(),內部實際上是打開並讀取文件,返回內容 self.redirect("http://www.cnblogs.com/suoning",permanent=False) # 跳轉重定向,參數表明是否永久重定向 name = self.get_argument("name") # 獲取客戶端傳入的參數值 name = self.get_arguments("name") # 獲取多個值,類別形式 file = self.request.files["filename"] # 獲取客戶端上傳的文件 raise tornado.web.HTTPError(403) # 返回錯誤信息給客戶端
對於一個請求的處理過程代碼調用次序以下:ios
initialize()
函數,這個函數的參數是 Application
配置中的關鍵字參數定義。(initialize
方法是 Tornado 1.1 中新添加的,舊版本中你須要重寫 __init__
以達到一樣的目的) initialize
方法通常只是把傳入的參數存到成員變量中,而不會產生一些輸出或者調用像 send_error
之類的方法。prepare()
。不管使用了哪一種 HTTP 方法,prepare
都會被調用到,所以這個方法一般會被定義在一個基類中,而後在子類中重用。prepare
能夠產生輸出信息。若是它調用了finish
(或send_error` 等函數),那麼整個處理流程就此結束。get()
、post()
、put()
等。若是 URL 的正則表達式模式中有分組匹配,那麼相關匹配會做爲參數傳入方法。重寫 initialize()
函數(會在建立RequestHandler對象後調用):git
class ProfileHandler(tornado.web.RequestHandler): def initialize(self,database): self.database = database def get(self): self.write("result:" + self.database) application = tornado.web.Application([ (r"/init", ProfileHandler, dict(database="database")) ])
Tornao中的模板語言和django中相似,模板引擎將模板文件載入內存,而後將數據嵌入其中,最終獲取到一個完整的字符串,再將字符串返回給請求者。github
Tornado 的模板支持「控制語句」和「表達語句」,控制語句是使用 {%
和 %}
包起來的 例如 {% if len(items) > 2 %}
。表達語句是使用 {{
和 }}
包起來的,例如 {{ items[0] }}。web
控制語句和對應的 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() app.py
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>Nick</title> </head> <body> <div> <ul> {% for item in list_info %} <li>{{item}}</li> {% end %} </ul> </div> </body> </html> index.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 的別名
其餘方法
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>Nick</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 %} index.html
<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>Nick</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> index.html
a.定義
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 escape.xhtml_escape('<h1>nick</h1>') #return escape.xhtml_escape('<h1>suoning</h1>') uimodules.py
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>Nick</title> <link href="{{static_url("commons.css")}}" rel="stylesheet" /> </head> <body> <h1>hello</h1> {% module custom(123) %} {{ tab() }} </body>
在應用配置 settings 中指定 static_path
選項來提供靜態文件服務;
在應用配置 settings 中指定 static_url_prefix
選項來提供靜態文件前綴服務;
在導入靜態文件時用 {{static_url('XX.css')}}
方式實現主動緩存靜態文件
settings = { 'template_path': 'views', 'static_path': 'static', 'static_url_prefix': '/static/', }
<head lang="en"> <title>Nick</title> <link href="{{static_url("commons.css")}}" rel="stylesheet" /> </head>
set_cookie
方法在用戶的瀏覽中設置 cookie;
get_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 中保存當前登錄用戶的 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 內部算法
加密Cookice的本質:
寫cookie過程:
讀cookie過程:
注:許多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 == 'nick' and password == 'nicknick': self.set_secure_cookie('login_user', 'nick') 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() 基於Cookie實現用戶驗證-Demo
#!/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 == 'nick' and password == 'nicknick': self.set_secure_cookie('login_user', 'nick') 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() 基於簽名Cookie實現用戶驗證-Demo
因爲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,猛擊這裏
當前已經認證的用戶信息都被保存在每個請求處理器的 self.current_user
當中, 同時在模板的 current_user
中也是。默認狀況下,current_user
爲 None
。
要在應用程序實現用戶認證的功能,你須要重寫請求處理中 get_current_user()
這 個方法,在其中斷定當前用戶的狀態,好比經過 cookie。下面的例子讓用戶簡單地使用一個 nickname 登錄應用,該登錄信息將被保存到 cookie 中:
class BaseHandler(tornado.web.RequestHandler): def get_current_user(self): return self.get_secure_cookie("user") class MainHandler(BaseHandler): def get(self): if not self.current_user: self.redirect("/login") return name = tornado.escape.xhtml_escape(self.current_user) self.write("Hello, " + name) class LoginHandler(BaseHandler): def get(self): self.write('<html><body><form action="/login" method="post">' 'Name: <input type="text" name="name">' '<input type="submit" value="Sign in">' '</form></body></html>') def post(self): self.set_secure_cookie("user", self.get_argument("name")) self.redirect("/") application = tornado.web.Application([ (r"/", MainHandler), (r"/login", LoginHandler), ], cookie_secret="61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=")
對於那些必需要求用戶登錄的操做,可使用裝飾器 tornado.web.authenticated
。 若是一個方法套上了這個裝飾器,可是當前用戶並無登錄的話,頁面會被重定向到 login_url
(應用配置中的一個選項),上面的例子能夠被改寫成:
class MainHandler(BaseHandler): @tornado.web.authenticated def get(self): name = tornado.escape.xhtml_escape(self.current_user) self.write("Hello, " + name) settings = { "cookie_secret": "61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=", "login_url": "/login", } application = tornado.web.Application([ (r"/", MainHandler), (r"/login", LoginHandler), ], **settings)
若是你使用 authenticated
裝飾器來裝飾 post()
方法,那麼在用戶沒有登錄的狀態下, 服務器會返回 403 錯誤。
Tornado 內部集成了對第三方認證形式的支持,好比 Google 的 OAuth 。參閱 auth
模塊 的代碼文檔以瞭解更多信息。 for more details. Checkauth
模塊以瞭解更多的細節。在 Tornado 的源碼中有一個 Blog 的例子,你也能夠從那裏看到 用戶認證的方法(以及如何在 MySQL 數據庫中保存用戶數據)。
跨站僞造請求(Cross-site request forgery), 簡稱爲 XSRF,是個性化 Web 應用中常見的一個安全問題。前面的連接也詳細講述了 XSRF 攻擊的實現方式。
當前防範 XSRF 的一種通用的方法,是對每個用戶都記錄一個沒法預知的 cookie 數據,而後要求全部提交的請求中都必須帶有這個 cookie 數據。若是此數據不匹配 ,那麼這個請求就多是被僞造的。
Tornado 有內建的 XSRF 的防範機制,要使用此機制,你須要在應用配置中加上 xsrf_cookies
設定:
settings = { "cookie_secret": "61oETzKXQAGaYdkL5gEmGeJJFuYh7EQnp2XdTP1o/Vo=", "login_url": "/login", "xsrf_cookies": True, } application = tornado.web.Application([ (r"/", MainHandler), (r"/login", LoginHandler), ], **settings)
若是設置了 xsrf_cookies
,那麼 Tornado 的 Web 應用將對全部用戶設置一個 _xsrf
的 cookie 值,若是 POST
PUT
DELET
請求中沒有這 個 cookie 值,那麼這個請求會被直接拒絕。若是你開啓了這個機制,那麼在全部 被提交的表單中,你都須要加上一個域來提供這個值。你能夠經過在模板中使用 專門的函數 xsrf_form_html()
來作到這一點:
<form action="/new_message" method="post"> {{ xsrf_form_html() }} <input type="text" name="message"/> <input type="submit" value="Post"/> </form>
若是你提交的是 AJAX 的 POST
請求,你仍是須要在每個請求中經過腳本添加上 _xsrf
這個值。下面是在 FriendFeed 中的 AJAX 的 POST
請求,使用了 jQuery 函數來爲全部請求組東添加 _xsrf
值:
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 + ")"));
}});
};
對於 PUT
和 DELETE
請求(以及不使用將 form 內容做爲參數的 POST
請求) 來講,你也能夠在 HTTP 頭中以 X-XSRFToken
這個參數傳遞 XSRF token。
若是你須要針對每個請求處理器定製 XSRF 行爲,你能夠重寫 RequestHandler.check_xsrf_cookie()
。例如你須要使用一個不支持 cookie 的 API, 你能夠經過將 check_xsrf_cookie()
函數設空來禁用 XSRF 保護機制。然而若是 你須要同時支持 cookie 和非 cookie 認證方式,那麼只要當前請求是經過 cookie 進行認證的,你就應該對其使用 XSRF 保護機制,這一點相當重要。
<!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> 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() Python
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <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> </html> HTML - XMLHttpRequest
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <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> </html> HTML - jQuery
<!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> HTML - iframe
#!/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()
Python
<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> 擴展:基於iframe實現Ajax上傳示例
安裝圖像處理模塊:pip3 install pillow
實例截圖:
驗證碼Demo源碼下載:猛擊這裏,注意導入模塊的路徑
#!/usr/bin/env python #-*- coding:utf-8 -*- """blog:http://www.cnblogs.com/suoning""" __author__ = 'Nick Suo' import tornado.web import tornado.ioloop import time import hashlib container = {} class Session: def __init__(self,handler): self.handler = handler self.random_str = None def __genarte_randmo_str(self): obj = hashlib.md5() obj.update(bytes(str(time.time()), encoding='utf-8')) random_str = obj.hexdigest() return random_str def __setitem__(self,key,value): if not self.random_str: random_str = self.handler.get_secure_cookie("__tt__") if not random_str: random_str = self.__genarte_randmo_str() container[random_str] = {} else: if random_str not in container.keys(): random_str = self.__genarte_randmo_str() container[random_str] = {} self.random_str = random_str container[self.random_str][key] = value self.handler.set_secure_cookie("__tt__",self.random_str,expires_days=None) def __getitem__(self,key): randmon_str = self.handler.get_secure_cookie("__tt__") randmon_str = str(randmon_str,encoding='utf-8') if not randmon_str: return None user_info_dic = container.get(randmon_str,None) if not user_info_dic: return None value = user_info_dic.get(key,None) return value class MyHandler(tornado.web.RequestHandler): def initialize(self): self.session = Session(self) class LoginHandler(MyHandler): def get(self, *args, **kwargs): self.render('login2.html') def post(self, *args, **kwargs): name = self.get_argument('user',None) pwd = self.get_argument('pwd',None) code = self.get_argument('code',None) if self.session['Check_Code'].upper() == code.upper(): self.write("successful") else: self.write("wrong") class CheckcodeHandler(MyHandler): def get(self, *args, **kwargs): import io import check_code mstream = io.BytesIO() img, code = check_code.create_validate_code() # 圖片和圖片上的碼 img.save(mstream, "GIF") self.session['Check_Code'] = code # 把驗證碼存入session self.write(mstream.getvalue()) # 寫入圖片 settings = { 'template_path':'views', 'static_path':'statics', 'cookie_secret':'suoning', } application = tornado.web.Application([ (r'/login',LoginHandler), (r'/check_code',CheckcodeHandler), ], **settings) if __name__ == '__main__': application.listen(8888) tornado.ioloop.IOLoop.instance().start() 驗證碼實例 python文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login by Nick</title> </head> <body> <form method="post" action="/login"> <p><input name="user" type="text" placeholder="用戶"/></p> <p><input name='pwd' type="text" placeholder="密碼"/></p> <p> <input name="code" type="text" placeholder="驗證碼"/> <img src="/check_code" onclick='ChangeCode();' id='imgCode'> </p> <input type="submit" value="Submit" /> <span style="color:red"></span> </form> <script> function ChangeCode() { // 刷新圖片 var code = document.getElementById('imgCode'); code.src += '?'; } </script> </body> </html> 驗證碼實例 HTML文件
當一個處理請求的行爲被執行以後,這個請求會自動地結束。由於 Tornado 當中使用了 一種非阻塞式的 I/O 模型,因此你能夠改變這種默認的處理行爲——讓一個請求一直保持 鏈接狀態,而不是立刻返回,直到一個主處理行爲返回。要實現這種處理方式,只須要使用 tornado.web.asynchronous
裝飾器就能夠了。
使用了這個裝飾器以後,你必須調用 self.finish()
已完成 HTTTP 請求,不然 用戶的瀏覽器會一直處於等待服務器響應的狀態:
class MainHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): self.write("Hello, world") self.finish()
下面是一個使用 Tornado 內置的異步請求 HTTP 客戶端去調用 FriendFeed 的 API 的例 子:
class MainHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): http = tornado.httpclient.AsyncHTTPClient() http.fetch("http://friendfeed-api.com/v2/feed/bret", callback=self.on_response) def on_response(self, response): if response.error: raise tornado.web.HTTPError(500) json = tornado.escape.json_decode(response.body) self.write("Fetched " + str(len(json["entries"])) + " entries " "from the FriendFeed API") self.finish()
例子中,當 get()
方法返回時,請求處理尚未完成。在 HTTP 客戶端執行它的回 調函數 on_response()
時,從瀏覽器過來的請求仍然是存在的,只有在顯式調用了 self.finish()
以後,纔會把響應返回到瀏覽器。
關於更多異步請求的高級例子,能夠參閱 demo 中的 chat
這個例子。它是一個使用 long polling 方式 的 AJAX 聊天室。若是你使用到了 long polling,你可能須要複寫on_connection_close()
, 這樣你能夠在客戶鏈接關閉之後作相關的清理動做。
何爲 Session?
是一種服務器端的機制,用於存儲特定的用戶會話所需的信息;必須依賴 cookice 。
Tornado 默認沒有提供 Session 機制,咱們能夠自定義以下:
#!/usr/bin/env python #-*- coding:utf-8 -*- """blog:http://www.cnblogs.com/suoning""" __author__ = 'Nick Suo' import tornado.web import tornado.ioloop import time import hashlib container = {} # 用於存放 Session,可放在數據庫,緩存等地 class Session: def __init__(self,handler): """ :param handler: 在 initialize 方法函數裏初始化,傳入當前對象self :param handler: 客戶端是否有指定 __ss__ flag """ self.handler = handler self.random_str = None def __genarte_randmo_str(self): """ 以當前時間戳生成隨機字符串 :return: 返回隨機字符串 """ obj = hashlib.md5() obj.update(bytes(str(time.time()), encoding='utf-8')) random_str = obj.hexdigest() return random_str def __setitem__(self,key,value): """ 設置 session 方法函數 :param key: 設置的 key :param value: 設置的 value """ if not self.random_str: random_str = self.handler.get_secure_cookie("__ss__") if not random_str: random_str = self.__genarte_randmo_str() container[random_str] = {} else: if random_str not in container.keys(): random_str = self.__genarte_randmo_str() container[random_str] = {} self.random_str = random_str container[self.random_str][key] = value self.handler.set_secure_cookie("__ss__",self.random_str) # expires_days=None def __getitem__(self,key): """ 獲取指定 session 方法函數 :param key: 要獲取的 key :return: 返回獲取到的值 """ randmon_str = self.handler.get_secure_cookie("__ss__") randmon_str = str(randmon_str,encoding='utf-8') if not randmon_str: return None user_info_dic = container.get(randmon_str, None) if not user_info_dic: return None value = user_info_dic.get(key, None) return value class MyHandler(tornado.web.RequestHandler): def initialize(self): self.session = Session(self) class IndexHandler(MyHandler): def get(self, *args, **kwargs): ...... result = self.session["name"] # 獲取 Session 方法函數 self.session['name'] = "Nick" # 設置 Session 方法函數 settings = { 'template_path':'views', 'static_path':'statics', 'cookie_secret':'suoning..................', } application = tornado.web.Application([ (r'/index',IndexHandler), ], **settings) if __name__ == '__main__': application.listen(8888) tornado.ioloop.IOLoop.instance().start()