1.Tornado
- Tornado:python編寫的web服務(wù)器兼web應(yīng)用框架
1.Tornado的優(yōu)勢(shì)
- 輕量級(jí)web框架
- 異步非阻塞IO處理方式
- 出色的抗負(fù)載能力
- 優(yōu)異的處理性能阀捅,不依賴多進(jìn)程/多線程故硅,一定程度上解決C10K問(wèn)題
- WSGI全棧替代產(chǎn)品,推薦同時(shí)使用其web框架和HTTP服務(wù)器
2.Tornado VS Django
- Django:重量級(jí)web框架糯崎,功能大而全拓哟,注重高效開發(fā)
- 內(nèi)置管理后臺(tái)
- 內(nèi)置封裝完善的ORM操作
- session功能
- 后臺(tái)管理
- 缺陷:高耦合
- Tornado:輕量級(jí)web框架想许,功能少而精,注重性能優(yōu)越
- HTTP服務(wù)器
- 異步編程
- WebSocket
- 缺陷:入門門檻較高
2.安裝
輸入命令:
pip install tornado
備注:
Tornado應(yīng)該運(yùn)行在類Unix平臺(tái)断序,為了達(dá)到最佳的性能和擴(kuò)展性流纹,僅推薦Linux和BSD(充分利用Linux的epoll工具和BSD的kqueue達(dá)到高性能處理的目的)
3.使用
1.Tornado入門程序 - (一)
#-*- coding:utf-8 -*-
import tornado.web
import tornado.ioloop
#定義處理類型
class IndexHandler(tornado.web.RequestHandler):
#添加一個(gè)處理get請(qǐng)求方式的方法
def get(self):
#向響應(yīng)中,添加數(shù)據(jù)
self.write('好看的皮囊千篇一律违诗,有趣的靈魂萬(wàn)里挑一漱凝。')
if __name__ == '__main__':
#創(chuàng)建一個(gè)應(yīng)用對(duì)象
app = tornado.web.Application([(r'/',IndexHandler)])
#綁定一個(gè)監(jiān)聽端口
app.listen(8888)
#啟動(dòng)web程序,開始監(jiān)聽端口的連接
tornado.ioloop.IOLoop.current().start()
1 .在pycharm中直接運(yùn)行代碼
2 .如果是在ubuntu诸迟,在命令窗口輸入python 文件名.py
4.Tornado 代碼解析
1.入門程序代碼解析
-
tornado.web:tornado的基礎(chǔ)web框架
-
RequestHandler
:封裝對(duì)請(qǐng)求處理的所有信息和處理方法 -
get/post/..
:封裝對(duì)應(yīng)的請(qǐng)求方式 -
write()
:封裝響應(yīng)信息茸炒,寫響應(yīng)信息的一個(gè)方法
-
-
tornado.ioloop:核心io循環(huán)模塊,封裝linux的epoll和BSD的kqueue阵苇, tornado高性能處理的核心壁公。
-
current()
返回當(dāng)前線程的IOLoop實(shí)例對(duì)象 -
start()
啟動(dòng)IOLoop實(shí)力對(duì)象的IO循環(huán)器瘪,開啟監(jiān)聽
-
2.httpserver底層處理
-
httpserver監(jiān)聽端口
tornado.httpserver.HTTPServer(app)
httpserver.listen(port)
-
httpserver實(shí)現(xiàn)多進(jìn)程操作
tornado.httpserver.HTTPServer(app)
httpserver.bind(port)
httpserver.start(0/None/<0/num)
# -*- coding:utf-8 -*-
from tornado.web import Application,RequestHandler
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer
class IndexHandler(RequestHandler):
def get(self):
self.write('給自己一點(diǎn)時(shí)間拥褂,理清所有的荒唐與期望。')
if __name__ == '__main__':
app = Application([(r'/',IndexHandler)])
http_server = HTTPServer(app)
#最原始的方式
http_server.bind(8888)
http_server.start(0)
#啟動(dòng)Ioloop輪循監(jiān)聽
IOLoop.current().start()
3.options配置
- 全局配置
tornado.options.define(
name, default, type, multiple, help
)
- 命令行參數(shù)轉(zhuǎn)換
tornado.options.parse_command_line()
#-*- coding:utf-8 -*- from tornado.web import RequestHandler,Application from tornado.ioloop import IOLoop from tornado.httpserver import HTTPServer import tornado.options #定義變量 tornado.options.define('port',default=8000,type=int,help="this is the port >for application") class IndexHandler(RequestHandler): def get(self): self.write('我們既然改變不了規(guī)則男翰,那就做到最好') if __name__ == '__main__': app = Application([(r'/',IndexHandler)]) tornado.options.parse_command_line() http_server = HTTPServer(app) http_server.bind(tornado.options.options.port) http_server.start(1) #啟動(dòng)IOLoop輪循監(jiān)聽 IOLoop.current().start()
- 配置文件
#即在當(dāng)前py文件目錄創(chuàng)建config文件快耿,并在py代碼中加入以下代碼囊陡,
tornado.options.parse_config_file("./config")
- 配置模塊:跟配置文件類似
4.application配置
- 程序調(diào)試之debug配置
#自動(dòng)重啟+取消緩存模板+取消緩存靜態(tài)文件+提供追蹤信息
tornado.web.Application([(..)], debug=True)
注:開發(fā)之初可以設(shè)置debug=True方便調(diào)試,開發(fā)完畢改為False.
- 路由信息初始化參數(shù)配置
tonado.web.Application([(r””, Handler, {k:v})])
def initialize(self, k)
#-*- coding:utf-8 -*- from tornado.web import RequestHandler,Application from tornado.ioloop import IOLoop from tornado.httpserver import HTTPServer from tornado.options import define,options define('port',default=8000,type=int) class IndexHandler(RequestHandler): def get(self): self.write('get-->先自沉穩(wěn)润努,而后愛人') class ArticleHandler(RequestHandler): def initialize(self,title): print('-->initialize()') self.title = title def get(self): self.write('你正在查看文章:%s'% self.title) if __name__ == '__main__': options.parse_command_line() app = Application([(r'/',IndexHandler),(r'/article',ArticleHandler,{'title':'你>希望自己成為什么樣的人关斜,最終就會(huì)成為那樣的人。'})],debug=True) http_server = HTTPServer(app) http_server.bind(options.port) http_server.start(1) IOLoop.current().start()
- 路由名稱設(shè)置及反解析
#名稱設(shè)置
tornado.web.Application([
url(r””, handler, {k,v}, name=“”)
])
#反解析操作
reverse_url(name)
# -*- coding:utf-8 -*- from tornado.web import Application, RequestHandler, url from tornado.ioloop import IOLoop from tornado.httpserver import HTTPServer from tornado.options import options,define define("port", default=8000, type=int) class IndexHandler(RequestHandler): def get(self): self.write("<a href='"+self.reverse_url("login")+"'>用戶登錄</a>") class RegistHandler(RequestHandler): def initialize(self, title): self.title = title def get(self): self.write("注冊(cè)業(yè)務(wù)處理:" + str(self.title)) class LoginHandler(RequestHandler): def get(self): self.write("用戶登錄頁(yè)面展示") def post(self): self.write("用戶登錄功能處理") if __name__ == "__main__": app = Application( [ (r"/", IndexHandler), (r"/regist", RegistHandler, {"title": "會(huì)員注冊(cè)"}), url(r"/login", LoginHandler, name="login"), ] ) http_server = HTTPServer(app) http_server.listen(8000) IOLoop.current().start()
5.參數(shù)傳遞
- get方式傳遞參數(shù)
get_query_arguments(name,default=_ARG_DEFAULT,strip=True)
get_query_argument(name ,strip=True)
# -*- coding:utf-8 -*- from tornado.web import Application, RequestHandler from tornado.ioloop import IOLoop from tornado.httpserver import HTTPServer from tornado.options import options, define define("port", default=8000, type=int) class IndexHandler(RequestHandler): def get(self): # 獲取get方式傳遞的參數(shù) username = self.get_query_argument("username") usernames = self.get_query_arguments("username") print (username) print (usernames) if __name__ == "__main__": app = Application([(r"/", IndexHandler)]) app.listen(8000) IOLoop.current().start()
- post方式傳遞參數(shù)
get_body_arguments(name, default=_ARG_DEFAULT,strip=True)
get_body_argument(name ,strip=True)
- 混合方式
get_arguments(..)/get_argument(..)
# -*- coding:utf-8 -*- from tornado.web import Application, RequestHandler from tornado.ioloop import IOLoop from tornado.options import options, define define("port", default=8000, type=int) class IndexHandler(RequestHandler): def get(self): # 獲取get方式的參數(shù) user = self.get_argument("user") print("get方式獲取參數(shù):" + str(user)) def post(self): # 獲取post方式的參數(shù) user = self.get_argument("user") print("post方式獲取參數(shù):" + user.encode("utf-8")) if __name__ == "__main__": app = Application([(r"/", IndexHandler)]) app.listen(8888) IOLoop.current().start()
- 其他參數(shù)
通過(guò)request獲取參數(shù)數(shù)據(jù)
method/host/uri/path/query/version/headers/body/remote_ip/files
6.響應(yīng)頭設(shè)置
- set_header(name, value)
- set_default_headers(self)
- add_header(name, value)
- clear_header(name)
# -*- coding:utf-8 -*-
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop
from tornado.options import options, define
define("port", default=8000, type=int)
class IndexHandler(RequestHandler):
def set_default_headers(self):
# 第二種響應(yīng)頭設(shè)置方式
print("---------> 響應(yīng)頭set_default_headers()執(zhí)行")
self.set_header("Content-type", "application/json; charset=utf-8")
self.set_header("js", "zj")
def get(self):
# 第一種操作響應(yīng)頭的方式:
# self.set_header("Content-type", "application/json")
print("---------->get方法執(zhí)行")
self.write("{'簡(jiǎn)書':'知幾'}")
self.set_header("jianshu", "zhiji")
if __name__ == "__main__":
app = Application([(r"/", IndexHandler)])
app.listen(8000)
IOLoop.current().start()
7.cookie操作
- cookies
set/get_cookie(name, value)
set/get_secure_cookie(name, value)
clear_cookie(name)
clear_all_cookie()
# -*- coding:utf-8 -*-
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop
from tornado.options import options, define
define("port", default=8000, type=int)
class IndexHandler(RequestHandler):
def get(self):
self.write("hello jianshu.com")
self.set_cookie("loginuser", "admin")
print self.get_cookie("loginuser")
print self.cookies
if __name__ == "__main__":
app = Application([(r"/", IndexHandler)])
app.listen(8000)
IOLoop.current().start()
8.響應(yīng)錯(cuò)誤碼 & 錯(cuò)誤描述
- set_status(status_code, reason=None)
# -*- coding:utf-8 -*-
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop
from tornado.options import options, define
define("port", default=8000, type=int)
class IndexHandler(RequestHandler):
def get(self):
self.write("hello 簡(jiǎn)書")
# self.set_status(404) # 標(biāo)準(zhǔn)錯(cuò)誤碼 無(wú)描述使用默認(rèn)描述
self.set_status(201, reason="zhiji is cool") # 自定義錯(cuò)誤碼痢畜,設(shè)置reason描述
# self.set_status(230) # 自定義錯(cuò)誤碼,無(wú)reason 報(bào)錯(cuò)
if __name__ == "__main__":
app = Application([(r"/", IndexHandler)])
app.listen(8000)
IOLoop.current().start()
- send_error(status_code, reason=None)
# -*- coding:utf-8 -*-
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop
from tornado.options import options, define
define("port", default=8000, type=int)
class IndexHandler(RequestHandler):
def get(self):
self.write("hello qikuedu.com")
self.send_error(500, reason="出錯(cuò)啦出錯(cuò)啦")
if __name__ == "__main__":
app = Application([(r"/", IndexHandler)])
app.listen(8000)
IOLoop.current().start()
- write_error(self, status_code, **kw)
# -*- coding:utf-8 -*-
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop
from tornado.options import options, define
define("port", default=8000, type=int)
class IndexHandler(RequestHandler):
def get(self):
self.write("hello qikuedu.com")
self.send_error(404, msg="頁(yè)面丟失", info="家里服務(wù)器搞對(duì)象去了")
def write_error(self, status_code, **kwargs):
self.write("<h1>出錯(cuò)啦,工程師MM正在趕來(lái)的途中...</h1>")
self.write("<p>錯(cuò)誤信息:%s</p>" % kwargs["msg"])
self.write("<p>錯(cuò)誤描述:%s</p>" % kwargs["info"])
if __name__ == "__main__":
app = Application([(r"/", IndexHandler)])
app.listen(8000)
IOLoop.current().start()