有個朋友讓我搞搞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('<html><body><form action="/" 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("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()
新聞熱點
疑難解答