有個朋友讓我搞搞tornado架構,說實話,這個架構我用的不多。。。
我就把自己的一些個營運研發相關的例子,分享給大家。
怎麼安裝tornado,我想大家都懂。
pip install tornado
再來說說他的一些個模組,官網有介紹的。我這裡再囉嗦的複讀機一下,裡面摻夾我的理解。
主要模組
web - FriendFeed 使用的基礎 Web 架構,包含了 Tornado 的大多數重要的功能,反正你進入就對了。
escape - XHTML, JSON, URL 的編碼/解碼方法
database - 對 MySQLdb 的簡單封裝,使其更容易使用,是個orm的東西。
template - 基於 Python 的 web 模板系統,類似jinja2
httpclient - 非阻塞式 HTTP 用戶端,它被設計用來和 web 及 httpserver 協同工作,這個類似加個urllib2
auth - 第三方認證的實現(包括 Google OpenID/OAuth、Facebook Platform、Yahoo BBAuth、FriendFeed OpenID/OAuth、Twitter OAuth)
locale - 針對本地化和翻譯的支援
options - 命令列和設定檔解析工具,針對伺服器環境做了最佳化,接受參數的
底層模組
httpserver - 服務於 web 模組的一個非常簡單的 HTTP 伺服器的實現
iostream - 對非阻塞式的 socket 的簡單封裝,以方便常用讀寫操作
ioloop - 核心的 I/O 迴圈
再來說說tornado接受請求的方式:
關於get的方式
class MainHandler(tornado.web.RequestHandler): def get(self): self.write("You requested the main page") class niubi(tornado.web.RequestHandler): def get(self, story_id): self.write("xiaorui.cc niubi'id is " + story_id) application = tornado.web.Application([ (r"/", MainHandler), (r"/niubi/([0-9]+)", niubi), ])
這樣我們訪問 /niubi/123123123 就會走niubi這個類,裡面的get參數。
關於post的方式
class MainHandler(tornado.web.RequestHandler): def get(self): self.write('') def post(self): self.set_header("Content-Type", "text/plain") self.write("xiaorui.cc and " + self.get_argument("message"))
在tornado裡面,一般get和post都在一個訪問路由裡面的,只是按照不同method來區分相應的。
扯淡的完了,大家測試下get和post。
import tornado.ioloop import tornado.web import json class hello(tornado.web.RequestHandler): def get(self): self.write('Hello,xiaorui.cc') class add(tornado.web.RequestHandler): def post(self): res = Add(json.loads(self.request.body)) self.write(json.dumps(res)) def Add(input): sum = input['num1'] + input['num2'] result = {} result['sum'] = sum return result application = tornado.web.Application([ (r"/", hello), (r"/add", add), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start()
#大家可以寫個form測試,也可以用curl -d測試