內(nèi)容原子官方文檔:
成都一家集口碑和實力的網(wǎng)站建設(shè)服務(wù)商,擁有專業(yè)的企業(yè)建站團隊和靠譜的建站技術(shù),10年企業(yè)及個人網(wǎng)站建設(shè)經(jīng)驗 ,為成都上千余家客戶提供網(wǎng)頁設(shè)計制作,網(wǎng)站開發(fā),企業(yè)網(wǎng)站制作建設(shè)等服務(wù),包括成都營銷型網(wǎng)站建設(shè),成都品牌網(wǎng)站建設(shè),同時也為不同行業(yè)的客戶提供網(wǎng)站設(shè)計制作、網(wǎng)站設(shè)計的服務(wù),包括成都電商型網(wǎng)站制作建設(shè),裝修行業(yè)網(wǎng)站制作建設(shè),傳統(tǒng)機械行業(yè)網(wǎng)站建設(shè),傳統(tǒng)農(nóng)業(yè)行業(yè)網(wǎng)站制作建設(shè)。在成都做網(wǎng)站,選網(wǎng)站制作建設(shè)服務(wù)商就選創(chuàng)新互聯(lián)建站。Tornado基礎(chǔ)
Tornado是一套web框架和異步網(wǎng)絡(luò)功能庫,使用非阻塞式IO,可支持數(shù)萬個活動連接。支持長活躍連接,支持 long polling長連接,支持WebSockets。
A web framework (including RequestHandler which is subclassed to create web applications, and various supporting classes).
Client- and server-side implementions of HTTP (HTTPServer and AsyncHTTPClient).
An asynchronous networking library (IOLoop and IOStream), which serve as the building blocks for the HTTP components and can also be used to implement other protocols.
A coroutine library (tornado.gen) which allows asynchronous code to be written in a more straightforward way than chaining callbacks.
●一個web框架,包含RequestHandler 用于創(chuàng)建web應(yīng)用程序。
●客戶端和服務(wù)端HTTP實現(xiàn)(HTTPServer and AsyncHTTPClient)。
●異步網(wǎng)絡(luò)庫(IOLoop and IOStream),可以用來建立HTTP組件,還可以實現(xiàn)其他協(xié)議。
●一個協(xié)程庫 (tornado.gen),可允許比鏈式回調(diào)地更加直接地編寫使用異步代碼。
Tornado可以作為WSGI容器,也可以被包含在其他WSGI容器。
的幾種異步接口:
Callback argument
Return a placeholder (Future, Promise, Deferred)
Deliver to a queue
Callback registry (e.g. POSIX signals)
●回調(diào)參數(shù)
●返回一個占位類 (Future, Promise, Deferred)
●遞交到隊列
●回調(diào)注冊(例如POSIX信號)
同步方式的代碼示例:
from tornado.httpclient import HTTPClientdef synchronous_fetch(url): http_client = HTTPClient() response = http_client.fetch(url) return response.body
回調(diào)方式的示例代碼:
from tornado.httpclient import AsyncHTTPClientdef asynchronous_fetch(url, callback): http_client = AsyncHTTPClient() def handle_response(response): callback(response.body) http_client.fetch(url, callback=handle_response)
使用Future的示例代碼:
from tornado.concurrent import Futuredef async_fetch_future(url): http_client = AsyncHTTPClient() my_future = Future() fetch_future = http_client.fetch(url) fetch_future.add_done_callback( lambda f: my_future.set_result(f.result())) return my_future
使用gen和協(xié)程方式的實例代碼:
from tornado import gen @gen.coroutine def fetch_coroutine(url): http_client = AsyncHTTPClient() response = yield http_client.fetch(url) raise gen.Return(response.body)
另一個gen和協(xié)程的實現(xiàn)代碼:
from tornado import gen@gen.coroutinedef fetch_coroutine(url): http_client = AsyncHTTPClient() response = yield http_client.fetch(url) return response.body
包含yield的函數(shù)是一個generator,它是異步的,返回generator對象無需等到運行完成。
def run(self): # send(x) makes the current yield return x. # It returns when the next yield is reached future = self.gen.send(self.next) def callback(f): self.next = f.result() self.run() future.add_done_callback(callback)
協(xié)程調(diào)用模式
和回調(diào)交互:將調(diào)用包裹在Task中,可以返回一個Future對象,并加入回調(diào)的參數(shù)。
@gen.coroutinedef call_task(): # Note that there are no parens on some_function. # This will be translated by Task into # some_function(other_args, callback=callback) yield gen.Task(some_function, other_args)
調(diào)用阻塞函數(shù):使用ThreadPoolExecutor,可以返回和協(xié)程兼容的Future。
thread_pool = ThreadPoolExecutor(4) @gen.coroutine def call_blocking(): yield thread_pool.submit(blocking_func, args)
并行執(zhí)行:協(xié)程裝飾器能識別類型為Futures的列表和字典,并且等待所有這些Future并行執(zhí)行完成
@gen.coroutine def parallel_fetch(url1, url2): resp1, resp2 = yield [http_client.fetch(url1), http_client.fetch(url2)]@gen.coroutinedef parallel_fetch_many(urls): responses = yield [http_client.fetch(url) for url in urls] # responses is a list of HTTPResponses in the same order@gen.coroutinedef parallel_fetch_dict(urls): responses = yield {url: http_client.fetch(url) for url in urls} # responses is a dict {url: HTTPResponse}
交替執(zhí)行:有些時候需要保存Future而不是讓他立即執(zhí)行,可以在等待時開始一個新的操作
@gen.coroutinedef get(self): fetch_future = self.fetch_next_chunk() while True: chunk = yield fetch_future if chunk is None: break self.write(chunk) fetch_future = self.fetch_next_chunk() yield self.flush()
循環(huán):需要從訪問的結(jié)果拆解循環(huán)條件,類似在Motor中的用法
import motordb = motor.MotorClient().test @gen.coroutine def loop_example(collection): cursor = db.collection.find() while (yield cursor.fetch_next): doc = cursor.next_object()
基本程序結(jié)構(gòu)
from tornado.ioloop import IOLoop from tornado.web import RequestHandler, Application, url class HelloHandler(RequestHandler): def get(self): self.write("Hello, world")def make_app(): return Application([ url(r"/", HelloHandler), ]) def main(): app = make_app() app.listen(8888) IOLoop.current().start()
Application和路由
class MainHandler(RequestHandler): def get(self): self.write('<a href="%s">link to story 1</a>' % self.reverse_url("story", "1"))class StoryHandler(RequestHandler): def initialize(self, db): self.db = db def get(self, story_id): self.write("this is story %s" % story_id) app = Application([ url(r"/", MainHandler), url(r"/story/([0-9]+)", StoryHandler, dict(db=db), name="story") ])
處理輸入請求
可以使用get_query_argument and get_body_argument方法,獲取get或表單的數(shù)據(jù)
class MyFormHandler(RequestHandler): def get(self): self.write('<html><body><form action="/myform" method="POST">' '<input type="text" name="message">' '<input type="submit" value="Submit">' '</form></body></html>') def post(self): self.set_header("Content-Type", "text/plain") self.write("You wrote " + self.get_body_argument("message"))
如果數(shù)據(jù)是json方式的
def prepare(self): if self.request.headers["Content-Type"].startswith("application/json"): self.json_args = json.loads(self.request.body) else: self.json_args = None
write_error - 輸出HTML的錯誤頁面。
on_connection_close - 客戶端斷開連接時調(diào)用; 應(yīng)用程序可以檢測這種情況 并終止后續(xù)的處理。 注意不能保證連接斷開的檢測是準確的。
get_current_user - 參看 User authentication (用戶授權(quán))
get_user_locale - 返回 Locale 對象給當前的用戶
set_default_headers - 可以用于設(shè)置附加的html相應(yīng)頭 (例如自定義Server 頭)
錯誤處理
RequestHandler.write_error 用來產(chǎn)生一個錯誤頁。
tornado.web.HTTPError用來產(chǎn)生錯誤狀態(tài)碼。
重定向
可以通過兩種方式實現(xiàn)重定向。
RequestHandler.redirect and with theRedirectHandler.
RedirectHandler用于配置重定向在路由中。
app = tornado.web.Application([ url(r"/app", tornado.web.RedirectHandler, dict(url="http://itunes.apple.com/my-app-id")), ])
支持正則表達式
app = tornado.web.Application([ url(r"/photos/(.*)", MyPhotoHandler), url(r"/pictures/(.*)", tornado.web.RedirectHandler, dict(url=r"/photos/\1")), ])
異步處理
異步處理通??梢允褂脙煞N形式:
coroutine 裝飾器 + yield關(guān)鍵字
tornado.web.asynchronous裝飾器 + callback ,請求會一直保持打開,callback完成返回時調(diào)用RequestHandler.finish ,響應(yīng)這時再發(fā)出
callback模式的示例,使用內(nèi)置的AsyncHTTPClient:
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()
協(xié)程模式的示例:
class MainHandler(tornado.web.RequestHandler): @tornado.gen.coroutine def get(self): http = tornado.httpclient.AsyncHTTPClient() response = yield http.fetch("http://friendfeed-api.com/v2/feed/bret") json = tornado.escape.json_decode(response.body) self.write("Fetched " + str(len(json["entries"])) + " entries " "from the FriendFeed API")
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國服務(wù)器、虛擬主機、免備案服務(wù)器”等云主機租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡單易用、服務(wù)可用性高、性價比高”等特點與優(yōu)勢,專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場景需求。
分享文章:Tornado學(xué)習(xí)筆記Tornado基礎(chǔ)1-創(chuàng)新互聯(lián)
本文來源:http://jinyejixie.com/article48/dpojep.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信公眾號、網(wǎng)站收錄、靜態(tài)網(wǎng)站、App設(shè)計、企業(yè)網(wǎng)站制作、全網(wǎng)營銷推廣
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容