python web框架之Tornado
說Tornado之前分享幾個前端不錯的網站:
-- Bootstraphttp://www.bootcss.com/-- Font Awesomehttp://fontawesome.io/-- bxsliderhttp://bxslider.com/-- jQuery EasyUIhttp://www.jeasyui.com/download/index.php-- jQuery UIhttp://jqueryui.com/-- parsleyjs http://parsleyjs.org/-- jQuery Validate http://jqueryvalidation.org/ View Codeweb框架的本質
總所周知,對于所有的Web應用,本質上其實就是一個socket服務端,用戶的瀏覽器其實就是一個socket客戶端。
#!/usr/bin/env python # _*_ coding:utf-8 _*_ import socketdef request_handler(client):a = client.recv(1024)client.send(bytes("HTTP/1.1 200 OK\r\n\r\n",encoding='utf-8'))client.send(bytes("hello",encoding="utf-8"))def main():sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)sock.bind(("127.0.0.1",8000))sock.listen(5)while True:con,add = sock.accept()request_handler(con)con.close()if __name__ == '__main__':main()上述通過socket來實現了其本質,而對于真實開發中的python web程序來說,一般會分為兩部分:服務器程序和應用程序。服務器程序負責對socket服務器進行封裝,并在請求到來時,對請求的各種數據進行整理。應用程序則負責具體的邏輯處理。為了方便應用程序的開發,就出現了眾多的Web框架,例如:Django、Flask、web.py 等。不同的框架有不同的開發方式,但是無論如何,開發出的應用程序都要和服務器程序配合,才能為用戶提供服務。這樣,服務器程序就需要為不同的框架提供不同的支持。這樣混亂的局面無論對于服務器還是框架,都是不好的。對服務器來說,需要支持各種不同框架,對框架來說,只有支持它的服務器才能被開發出的應用使用。這時候,標準化就變得尤為重要。我們可以設立一個標準,只要服務器程序支持這個標準,框架也支持這個標準,那么他們就可以配合使用。一旦標準確定,雙方各自實現。這樣,服務器可以支持更多支持標準的框架,框架也可以使用更多支持標準的服務器。
WSGI(Web Server Gateway Interface)是一種規范,它定義了使用python編寫的web app與web server之間接口格式,實現web app與web server間的解耦。
python標準庫提供的獨立WSGI服務器稱為wsgiref。
2.x環境運行
from wsgiref.simple_server import make_serverdef RunServer(environ, start_response):start_response('200 OK', [('Content-Type', 'text/html')])return '<h1>Hello, web!</h1>'if __name__ == '__main__':httpd = make_server('', 8888, RunServer)httpd.serve_forever()自定義Web框架
#!/usr/bin/env python # _*_ coding:utf-8 _*_from wsgiref.simple_server import make_serverdef index():return "hi"URLS = {"/index":index, }def RunServer(environ, start_response): #environ 封裝了請求頭信息start_response('200 OK', [('Content-Type', 'text/html')])url = environ["PATH_INFO"]if url in URLS.keys():ret=URLS[url]()else:ret = "404"return retif __name__ == '__main__':httpd = make_server('', 8000, RunServer)httpd.serve_forever()在上一步驟中,對于所有的index返回給用戶瀏覽器一個簡單的字符串,在現實的Web請求中一般會返回一個復雜的符合HTML規則的字符串,所以我們一般將要返回給用戶的HTML寫在指定文件中,然后再返回。如:
<!DOCTYPE html> <html> <head lang="en"><meta charset="UTF-8"><title></title> </head> <body><form><input type="text" /><input type="text" /><input type="submit" /></form> </body> </html> 返回表單 #!/usr/bin/env python # _*_ coding:utf-8 _*_from wsgiref.simple_server import make_serverdef login():file_list = open("temp/s2.html",'r')data = file_list.read()return datadef index():file_list = open("temp/s1.html",'r')data = file_list.read()return dataURLS = {"/index":index,"/login":login, }def RunServer(environ, start_response):start_response('200 OK', [('Content-Type', 'text/html')])url = environ["PATH_INFO"]if url in URLS.keys():ret=URLS[url]()else:ret = "404"return retif __name__ == '__main__':httpd = make_server('', 8000, RunServer)httpd.serve_forever()對于上述代碼,雖然可以返回給用戶HTML的內容以現實復雜的頁面,但是還是存在問題:如何給用戶返回動態內容?
- 自定義一套特殊的語法,進行替換
- 使用開源工具jinja2,遵循其指定語法
?
#!/usr/bin/env python # _*_ coding:utf-8 _*_from wsgiref.simple_server import make_server from jinja2 import Templatedef index():file_list = open("temp/s3.html",'r')file_text = file_list.read()temp = Template(file_text)data = temp.render(name="john Doe",user_list = ['tangseng','wukong'])return data.encode("utf-8")def login():file_list = open("temp/s2.html",'r')data = file_list.read()return dataURLS = {"/index":index,"/login":login, }def RunServer(environ, start_response):start_response('200 OK', [('Content-Type', 'text/html')])url = environ["PATH_INFO"]if url in URLS.keys():ret=URLS[url]()else:ret = "404"return retif __name__ == '__main__':httpd = make_server('', 8000, RunServer)httpd.serve_forever()遵循jinja2的語法規則,其內部會對指定的語法進行相應的替換,從而達到動態的返回內容
Tornado 前戲
執行字符串表示的函數,并為該函數提供全局變量
本篇的內容從題目中就可以看出來,就是為之后剖析tornado模板做準備,也是由于該知識點使用的巧妙,所有就單獨用一篇來介紹了。廢話不多說,直接上代碼:
#!usr/bin/env python #coding:utf-8namespace = {'name':'wukong','data':[18,73,84]}code = '''def hellocute():return "name %s ,age %d" %(name,data[0],) '''func = compile(code, '<string>', "exec")exec func in namespaceresult = namespace['hellocute']()此段代碼的執行結果是:name wukong,age 18
上述代碼解析:
- 第6行,code是一個字符串,該字符串的內容是一個函數體。
- 第8行,將code字符串編譯成函數 hello
- 第10行,將函數 hello 添加到namespace字典中(key為hello),同時也將python的所有內置函數添加到namespace字段中(key為__builtins__),如此一來,namespace中的內容好比是一個個的全局變量,即
- 第12行,執行Hello函數并將返回值復制給result
- 第14行,輸入result
這段代碼用的很是巧妙有木有,亮瞎狗眼有木有,居然把字符串變成了函數并且還為該函數提供了全局變量。對于該功能,它就是python的web框架中模板語言部分至關重要的部分,因為在模板處理過程中,首先會讀取html文件,然后分割html文件,再然后講分割的文件組成一個字符串表示的函數,再再然后就是利用上述方法執行字符串表示的函數。
? ?快速上手Tornado
Tornado?是?FriendFeed?使用的可擴展的非阻塞式 web 服務器及其相關工具的開源版本。這個 Web 框架看起來有些像web.py?或者?Google 的 webapp,不過為了能有效利用非阻塞式服務器環境,這個 Web 框架還包含了一些相關的有用工具 和優化。
Tornado 和現在的主流 Web 服務器框架(包括大多數 Python 的框架)有著明顯的區別:它是非阻塞式服務器,而且速度相當快。得利于其 非阻塞的方式和對?epoll?的運用,Tornado 每秒可以處理數以千計的連接,這意味著對于實時 Web 服務來說,Tornado 是一個理想的 Web 框架。我們開發這個 Web 服務器的主要目的就是為了處理 FriendFeed 的實時功能 ——在 FriendFeed 的應用里每一個活動用戶都會保持著一個服務器連接。(關于如何擴容 服務器,以處理數以千計的客戶端的連接的問題,請參閱?C10K problem。)
?一、安裝如下:
pip install tornado 源碼安裝https://pypi.python.org/packages/source/t/tornado/tornado-4.3.tar.gz第一次運行Tornado代碼:
#!/usr/bin/env python # -*- coding:utf-8 -*-import tornado.ioloop import tornado.webclass MainHandler(tornado.web.RequestHandler):def get(self):self.write("Hello, world")application = tornado.web.Application([(r"/index", MainHandler), ])if __name__ == "__main__":application.listen(8888)tornado.ioloop.IOLoop.instance().start()第一步:執行腳本,監聽 8888 端口
第二步:瀏覽器客戶端訪問 /index ?--> ?http://127.0.0.1:8888/index
第三步:服務器接受請求,并交由對應的類處理該請求
第四步:類接受到請求之后,根據請求方式(post / get / delete ...)的不同調用并執行相應的方法
第五步:方法返回值的字符串內容發送瀏覽器
#!/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 genimport uimodules as md import uimethods as mtclass MainHandler(tornado.web.RequestHandler):@asynchronous@gen.coroutinedef 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.bodysettings = {'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() 異步非阻塞?二、路由系統
路由系統其實就是 url 和 類 的對應關系,這里不同于其他框架,其他很多框架均是 url 對應 函數,Tornado中每個url對應的是一個類。
#!/usr/bin/env python # _*_ coding:utf-8 _*_import tornado.ioloop import tornado.webclass LoginHandler(tornado.web.RequestHandler):def get(self, *args, **kwargs):self.render("s2.html")class IndexHandler(tornado.web.RequestHandler):def get(self, *args, **kwargs):self.render("index.html") #路由系統 settings = {"template_path":"templates",}application = tornado.web.Application([(r"/index",IndexHandler),(r"/login",LoginHandler), ])if __name__ == '__main__':httpd = 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?語句實現了模板繼承。這些在?template?模塊?的代碼文檔中有著詳細的描述。
1.基本使用
#!/usr/bin/env python # -*- coding:utf-8 -*-import tornado.ioloop import tornado.webclass 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 <!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" /> </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> index在模板中默認提供了一些函數、字段、類以供模板使用:
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 的別名 其他方法2.母板
<!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> 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.html3.導入
<!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> index.html4.自定義UIMethod以UIModule
Tornado默認提供的這些功能其實本質上就是 UIMethod 和 UIModule,我們也可以自定義從而實現類似于Django的simple_tag的功能:
1、定義
# uimethods.pydef tab(self):return 'UIMethod' uimethods.py #!/usr/bin/env python # -*- coding:utf-8 -*- from tornado.web import UIModule from tornado import escapeclass custom(UIModule):def render(self, *args, **kwargs):return escape.xhtml_escape('<h1>wukong</h1>')#return escape.xhtml_escape('<h1>wukong</h1>') uimmodule注冊
#!/usr/bin/env python # -*- coding:utf-8 -*- #!/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 mtclass 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() main.py使用
<!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> index四、靜態文件
?
對于靜態文件,可以配置靜態文件的目錄和前段使用時的前綴,并且Tornaodo還支持靜態文件緩存。
#!/usr/bin/env python # -*- coding:utf-8 -*-import tornado.ioloop import tornado.webclass MainHandler(tornado.web.RequestHandler):def get(self):self.render('home/index.html')settings = {'template_path': 'template','static_path': 'static', //靜態資源的的路徑比如 css,js'static_url_prefix': '/static/', // 靜態資源的的 URL 前綴 }application = tornado.web.Application([(r"/index", MainHandler), ], **settings)if __name__ == "__main__":application.listen(80)tornado.ioloop.IOLoop.instance().start() View Code備注:靜態文件緩存的實現
?
五、cookie
Tornado中可以對cookie進行操作,并且還可以對cookie進行簽名以放置偽造。
a、基本操作
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!") View Codeb、加密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=")//隨意增加 Code 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_VERSIONif clock is None:clock = time.timetimestamp = 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 valueelif 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 + signatureelse: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 Nonesignature = _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 Nonetimestamp = int(parts[1])if timestamp < clock() - max_age_days * 86400:gen_log.warning("Expired cookie %r", value)return Noneif 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 Noneif parts[1].startswith(b"0"):gen_log.warning("Tampered cookie %r", value)return Nonetry:return base64.b64decode(parts[0])except Exception:return Nonedef _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, restrest = value[2:] # remove version numberkey_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_sigdef _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 Nonesigned_string = value[:-len(passed_sig)]if isinstance(secret, dict):try:secret = secret[key_version]except KeyError:return Noneexpected_sig = _create_signature_v2(secret, signed_string)if not _time_independent_equals(passed_sig, expected_sig):return Noneif name_field != utf8(name):return Nonetimestamp = int(timestamp)if timestamp < clock() - max_age_days * 86400:# The signature has expired.return Nonetry:return base64.b64decode(value_field)except Exception:return Nonedef get_signature_key_version(value):value = utf8(value)version = _get_version(value)if version < 2:return Nonetry:key_version, _, _, _, _ = _decode_fields_v2(value)except ValueError:return Nonereturn key_version 算法解密簽名Cookie的本質是:
寫cookie過程:將值進行base64加密 對除值以外的內容進行簽名,哈希算法(無法逆向解析) 拼接 簽名 + 加密值 讀cookie過程:讀取 簽名 + 加密值 對簽名進行驗證 base64解密,獲取值內容注:許多API驗證機制和安全cookie的實現機制相同。
#!/usr/bin/env python # -*- coding:utf-8 -*-import tornado.ioloop import tornado.webclass 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 == 'wukong' 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() 基于cookie進行用戶驗證 #!/usr/bin/env python # -*- coding:utf-8 -*-import tornado.ioloop import tornado.webclass BaseHandler(tornado.web.RequestHandler):def get_current_user(self):return self.get_secure_cookie("login_user")class MainHandler(BaseHandler):@tornado.web.authenticateddef get(self):login_user = self.current_userself.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 == 'wukong' 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() Demo-Toando內部提供基于cookie進行用戶驗證3、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(); }對于參數:
- domain ? 指定域名下的cookie
- path ? ? ? 域名下指定url中的cookie
- secure ? ?https使用
注:jQuery中也有指定的插件 jQuery Cookie 專門用于操作cookie,猛擊這里
六、CSRF
Tornado中的夸張請求偽造和Django中的相似,跨站偽造請求(Cross-site request forgery)
限制與POST請求
View Code 普通表單使用 ajax使用注:Ajax使用時,本質上就是去獲取本地的cookie,攜帶cookie再來發送請求
七、上傳文件
1、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> html #!/usr/bin/env python # -*- coding:utf-8 -*-import tornado.ioloop import tornado.webclass 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() python2、AJAX上傳
<!DOCTYPE html> <html> <head lang="en"><meta charset="UTF-8"><title></title> </head> <body><input type="file" id="img" /><input type="button" οnclick="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" οnclick="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 datacontentType: false, // tell jQuery not to set contentTypesuccess: 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" οnclick="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.webclass 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上傳示例八、驗證碼
驗證碼原理在于后臺自動創建一張帶有隨機內容的圖片,然后將內容通過img標簽輸出到頁面。
安裝圖像處理模塊:
pip3 install pillow示例截圖:
驗證碼Demo源碼下載:猛擊這里
源碼中有兩個文件要注意Monaco.ttf和check_code.py 要引入到工程內;demo:
自定義Web組件
一、Session
1、面向對象基礎
面向對象中通過索引的方式訪問對象,需要內部實現 __getitem__ 、__delitem__、__setitem__方法
#!/usr/bin/env python # -*- coding:utf-8 -*-class Foo(object):def __getitem__(self, key):print '__getitem__',keydef __setitem__(self, key, value):print '__setitem__',key,valuedef __delitem__(self, key):print '__delitem__',keyobj = Foo() result = obj['k1'] #obj['k2'] = 'wupeiqi' #del obj['k1'] View Code2、Tornado擴展
Tornado框架中,默認執行Handler的get/post等方法之前默認會執行 initialize方法,所以可以通過自定義的方式使得所有請求在處理前執行操作...
class BaseHandler(tornado.web.RequestHandler):def initialize(self):self.xxoo = "wupeiqi"class MainHandler(BaseHandler):def get(self):print(self.xxoo)self.write('index')class IndexHandler(BaseHandler):def get(self):print(self.xxoo)self.write('index') View Code3、session
session其實就是定義在服務器端用于保存用戶會話的容器,其必須依賴cookie才能實現。
import hashlib import timecontainer = {} class Session:def __init__(self, handler):self.handler = handlerself.random_str = Nonedef __genarate_random_str(self):'''用于生成加密字符串:return:'''obj = hashlib.md5()obj.update(bytes(str(time.time()), encoding='utf-8'))random_str = obj.hexdigest()return random_strdef __setitem__(self, key, value):# 在container中加入隨機字符串# 定義專屬于自己的數據# 在客戶端中寫入隨機字符串# 判斷,請求的用戶是否已有隨機字符串if not self.random_str:random_str = self.handler.get_cookie('__kakaka__')if not random_str:random_str = self.__genarate_random_str()container[random_str] = {}else:# 客戶端有隨機字符串if random_str in container.keys(): #判斷字符串是否在container中passelse:random_str = self.__genarate_random_str() #生成字符串container[random_str] = {} #生成專屬的字典self.random_str = random_str # self.random_str = asdfasdfasdfasdf container[self.random_str][key] = valueself.handler.set_cookie("__kakaka__", self.random_str)def __getitem__(self,key):# 獲取客戶端的隨機字符串# 從container中獲取專屬于我的數據# 專屬信息【key】random_str = self.handler.get_cookie("__kakaka__")if not random_str:return None# 客戶端有隨機字符串user_info_dict = container.get(random_str,None)if not user_info_dict:return Nonevalue = user_info_dict.get(key, None)return value View Code4、分布式Session
#!/usr/bin/env python #coding:utf-8import sys import math from bisect import bisectif sys.version_info >= (2, 5):import hashlibmd5_constructor = hashlib.md5 else:import md5md5_constructor = md5.newclass HashRing(object):"""一致性哈希"""def __init__(self,nodes):'''初始化nodes : 初始化的節點,其中包含節點已經節點對應的權重默認每一個節點有32個虛擬節點對于權重,通過多創建虛擬節點來實現如:nodes = [{'host':'127.0.0.1:8000','weight':1},{'host':'127.0.0.1:8001','weight':2},{'host':'127.0.0.1:8002','weight':1},]'''self.ring = dict()self._sorted_keys = []self.total_weight = 0self.__generate_circle(nodes)def __generate_circle(self,nodes):for node_info in nodes:self.total_weight += node_info.get('weight',1)for node_info in nodes:weight = node_info.get('weight',1)node = node_info.get('host',None)virtual_node_count = math.floor((32*len(nodes)*weight) / self.total_weight)for i in xrange(0,int(virtual_node_count)):key = self.gen_key_thirty_two( '%s-%s' % (node, i) )if self._sorted_keys.__contains__(key):raise Exception('該節點已經存在.')self.ring[key] = nodeself._sorted_keys.append(key)def add_node(self,node):''' 新建節點node : 要添加的節點,格式為:{'host':'127.0.0.1:8002','weight':1},其中第一個元素表示節點,第二個元素表示該節點的權重。'''node = node.get('host',None)if not node:raise Exception('節點的地址不能為空.')weight = node.get('weight',1)self.total_weight += weightnodes_count = len(self._sorted_keys) + 1virtual_node_count = math.floor((32 * nodes_count * weight) / self.total_weight)for i in xrange(0,int(virtual_node_count)):key = self.gen_key_thirty_two( '%s-%s' % (node, i) )if self._sorted_keys.__contains__(key):raise Exception('該節點已經存在.')self.ring[key] = nodeself._sorted_keys.append(key)def remove_node(self,node):''' 移除節點node : 要移除的節點 '127.0.0.1:8000''''for key,value in self.ring.items():if value == node:del self.ring[key]self._sorted_keys.remove(key)def get_node(self,string_key):'''獲取 string_key 所在的節點'''pos = self.get_node_pos(string_key)if pos is None:return Nonereturn self.ring[ self._sorted_keys[pos]].split(':')def get_node_pos(self,string_key):'''獲取 string_key 所在的節點的索引'''if not self.ring:return Nonekey = self.gen_key_thirty_two(string_key)nodes = self._sorted_keyspos = bisect(nodes, key)return posdef gen_key_thirty_two(self, key):m = md5_constructor()m.update(key)return long(m.hexdigest(), 16)def gen_key_sixteen(self,key):b_key = self.__hash_digest(key)return self.__hash_val(b_key, lambda x: x)def __hash_val(self, b_key, entry_fn):return (( b_key[entry_fn(3)] << 24)|(b_key[entry_fn(2)] << 16)|(b_key[entry_fn(1)] << 8)| b_key[entry_fn(0)] )def __hash_digest(self, key):m = md5_constructor()m.update(key)return map(ord, m.digest())""" nodes = [{'host':'127.0.0.1:8000','weight':1},{'host':'127.0.0.1:8001','weight':2},{'host':'127.0.0.1:8002','weight':1}, ]ring = HashRing(nodes) result = ring.get_node('98708798709870987098709879087') print result""" 一致性哈西 from hashlib import sha1 import os, timecreate_session_id = lambda: sha1('%s%s' % (os.urandom(16), time.time())).hexdigest()class Session(object):session_id = "__sessionId__"def __init__(self, request):session_value = request.get_cookie(Session.session_id)if not session_value:self._id = create_session_id()else:self._id = session_valuerequest.set_cookie(Session.session_id, self._id)def __getitem__(self, key):# 根據 self._id ,在一致性哈西中找到其對應的服務器IP# 找到相對應的redis服務器,如: r = redis.StrictRedis(host='localhost', port=6379, db=0)# 使用python redis api 鏈接# 獲取數據,即:# return self._redis.hget(self._id, name)def __setitem__(self, key, value):# 根據 self._id ,在一致性哈西中找到其對應的服務器IP# 使用python redis api 鏈接# 設置session# self._redis.hset(self._id, name, value)def __delitem__(self, key):# 根據 self._id 找到相對應的redis服務器# 使用python redis api 鏈接# 刪除,即:return self._redis.hdel(self._id, name) session二、表單驗證
在Web程序中往往包含大量的表單驗證的工作,如:判斷輸入是否為空,是否符合規則。
<!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><form action="/index" method="post"><p>hostname: <input type="text" name="host" /> </p><p>ip: <input type="text" name="ip" /> </p><p>port: <input type="text" name="port" /> </p><p>phone: <input type="text" name="phone" /> </p><input type="submit" /></form> </body> </html> HTML #!/usr/bin/env python # -*- coding:utf-8 -*-import tornado.ioloop import tornado.web from hashlib import sha1 import os, time import reclass 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_valid(self, request):form_dict = self.__dict__for key, regular in form_dict.items():post_value = request.get_argument(key)# 讓提交的數據 和 定義的正則表達式進行匹配ret = re.match(regular, post_value)print key,ret,post_valueclass MainHandler(tornado.web.RequestHandler):def get(self):self.render('index.html')def post(self, *args, **kwargs):obj = MainForm()result = obj.check_valid(self)self.write('ok')settings = {'template_path': 'template','static_path': 'static','static_url_prefix': '/static/','cookie_secret': 'aiuasdhflashjdfoiuashdfiuh','login_url': '/login' }application = tornado.web.Application([(r"/index", MainHandler), ], **settings)if __name__ == "__main__":application.listen(8888)tornado.ioloop.IOLoop.instance().start() Python由于驗證規則可以代碼重用,所以可以如此定義:
#!/usr/bin/env python # -*- coding:utf-8 -*-import tornado.ioloop import tornado.web import reclass Field(object):def __init__(self, error_msg_dict, required):self.id_valid = Falseself.value = Noneself.error = Noneself.name = Noneself.error_msg = error_msg_dictself.required = requireddef match(self, name, value):self.name = nameif not self.required:self.id_valid = Trueself.value = valueelse:if not value:if self.error_msg.get('required', None):self.error = self.error_msg['required']else:self.error = "%s is required" % nameelse:ret = re.match(self.REGULAR, value)if ret:self.id_valid = Trueself.value = ret.group()else:if self.error_msg.get('valid', None):self.error = self.error_msg['valid']else:self.error = "%s is invalid" % nameclass IPField(Field):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, error_msg_dict=None, required=True):error_msg = {} # {'required': 'IP不能為空', 'valid': 'IP格式錯誤'}if error_msg_dict:error_msg.update(error_msg_dict)super(IPField, self).__init__(error_msg_dict=error_msg, required=required)class IntegerField(Field):REGULAR = "^\d+$"def __init__(self, error_msg_dict=None, required=True):error_msg = {'required': '數字不能為空', 'valid': '數字格式錯誤'}if error_msg_dict:error_msg.update(error_msg_dict)super(IntegerField, self).__init__(error_msg_dict=error_msg, required=required)class CheckBoxField(Field):def __init__(self, error_msg_dict=None, required=True):error_msg = {} # {'required': 'IP不能為空', 'valid': 'IP格式錯誤'}if error_msg_dict:error_msg.update(error_msg_dict)super(CheckBoxField, self).__init__(error_msg_dict=error_msg, required=required)def match(self, name, value):self.name = nameif not self.required:self.id_valid = Trueself.value = valueelse:if not value:if self.error_msg.get('required', None):self.error = self.error_msg['required']else:self.error = "%s is required" % nameelse:if isinstance(name, list):self.id_valid = Trueself.value = valueelse:if self.error_msg.get('valid', None):self.error = self.error_msg['valid']else:self.error = "%s is invalid" % nameclass FileField(Field):REGULAR = "^(\w+\.pdf)|(\w+\.mp3)|(\w+\.py)$"def __init__(self, error_msg_dict=None, required=True):error_msg = {} # {'required': '數字不能為空', 'valid': '數字格式錯誤'}if error_msg_dict:error_msg.update(error_msg_dict)super(FileField, self).__init__(error_msg_dict=error_msg, required=required)def match(self, name, value):self.name = nameself.value = []if not self.required:self.id_valid = Trueself.value = valueelse:if not value:if self.error_msg.get('required', None):self.error = self.error_msg['required']else:self.error = "%s is required" % nameelse:m = re.compile(self.REGULAR)if isinstance(value, list):for file_name in value:r = m.match(file_name)if r:self.value.append(r.group())self.id_valid = Trueelse:self.id_valid = Falseif self.error_msg.get('valid', None):self.error = self.error_msg['valid']else:self.error = "%s is invalid" % namebreakelse:if self.error_msg.get('valid', None):self.error = self.error_msg['valid']else:self.error = "%s is invalid" % namedef save(self, request, upload_path=""):file_metas = request.files[self.name]for meta in file_metas:file_name = meta['filename']with open(file_name,'wb') as up:up.write(meta['body'])class Form(object):def __init__(self):self.value_dict = {}self.error_dict = {}self.valid_status = Truedef validate(self, request, depth=10, pre_key=""):self.initialize()self.__valid(self, request, depth, pre_key)def initialize(self):passdef __valid(self, form_obj, request, depth, pre_key):"""驗證用戶表單請求的數據:param form_obj: Form對象(Form派生類的對象):param request: Http請求上下文(用于從請求中獲取用戶提交的值):param depth: 對Form內容的深度的支持:param pre_key: Html中name屬性值的前綴(多層Form時,內部遞歸時設置,無需理會):return: 是否驗證通過,True:驗證成功;False:驗證失敗"""depth -= 1if depth < 0:return Noneform_field_dict = form_obj.__dict__for key, field_obj in form_field_dict.items():print key,field_objif isinstance(field_obj, Form) or isinstance(field_obj, Field):if isinstance(field_obj, Form):# 獲取以key開頭的所有的值,以參數的形式傳至self.__valid(field_obj, request, depth, key)continueif pre_key:key = "%s.%s" % (pre_key, key)if isinstance(field_obj, CheckBoxField):post_value = request.get_arguments(key, None)elif isinstance(field_obj, FileField):post_value = []file_list = request.request.files.get(key, None)for file_item in file_list:post_value.append(file_item['filename'])else:post_value = request.get_argument(key, None)print post_value# 讓提交的數據 和 定義的正則表達式進行匹配 field_obj.match(key, post_value)if field_obj.id_valid:self.value_dict[key] = field_obj.valueelse:self.error_dict[key] = field_obj.errorself.valid_status = Falseclass ListForm(object):def __init__(self, form_type):self.form_type = form_typeself.valid_status = Trueself.value_dict = {}self.error_dict = {}def validate(self, request):name_list = request.request.arguments.keys() + request.request.files.keys()index = 0flag = Falsewhile True:pre_key = "[%d]" % indexfor name in name_list:if name.startswith(pre_key):flag = Truebreakif flag:form_obj = self.form_type()form_obj.validate(request, depth=10, pre_key="[%d]" % index)if form_obj.valid_status:self.value_dict[index] = form_obj.value_dictelse:self.error_dict[index] = form_obj.error_dictself.valid_status = Falseelse:breakindex += 1flag = Falseclass MainForm(Form):def __init__(self):# self.ip = IPField(required=True)# self.port = IntegerField(required=True)# self.new_ip = IPField(required=True)# self.second = SecondForm()self.fff = FileField(required=True)super(MainForm, self).__init__()# # class SecondForm(Form): # # def __init__(self): # self.ip = IPField(required=True) # self.new_ip = IPField(required=True) # # super(SecondForm, self).__init__()class MainHandler(tornado.web.RequestHandler):def get(self):self.render('index.html')def post(self, *args, **kwargs):# for i in dir(self.request):# print i# print self.request.arguments# print self.request.files# print self.request.query# name_list = self.request.arguments.keys() + self.request.files.keys()# print name_list# list_form = ListForm(MainForm)# list_form.validate(self)# # print list_form.valid_status# print list_form.value_dict# print list_form.error_dict# obj = MainForm()# obj.validate(self)# # print "驗證結果:", obj.valid_status# print "符合驗證結果:", obj.value_dict# print "錯誤信息:"# for key, item in obj.error_dict.items():# print key,item# print self.get_arguments('favor'),type(self.get_arguments('favor'))# print self.get_argument('favor'),type(self.get_argument('favor'))# print type(self.get_argument('fff')),self.get_argument('fff')# print self.request.files# obj = MainForm()# obj.validate(self)# print obj.valid_status# print obj.value_dict# print obj.error_dict# print self.request,type(self.request)# obj.fff.save(self.request)# from tornado.httputil import HTTPServerRequest# name_list = self.request.arguments.keys() + self.request.files.keys()# print name_list# print self.request.files,type(self.request.files)# print len(self.request.files.get('fff'))# obj = MainForm()# obj.validate(self)# print obj.valid_status# print obj.value_dict# print obj.error_dict# obj.fff.save(self.request)self.write('ok')settings = {'template_path': 'template','static_path': 'static','static_url_prefix': '/static/','cookie_secret': 'aiuasdhflashjdfoiuashdfiuh','login_url': '/login' }application = tornado.web.Application([(r"/index", MainHandler), ], **settings)if __name__ == "__main__":application.listen(8888)tornado.ioloop.IOLoop.instance().start() View Code轉載于:https://www.cnblogs.com/yyyg/p/5690427.html
總結
以上是生活随笔為你收集整理的python web框架之Tornado的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux下查看/管理当前登录用户及用户
- 下一篇: 关系表达式的计算