asyncio 是 Python 3.4版本引入的標(biāo)準(zhǔn)庫,直接內(nèi)置了對(duì)異步IO的支持。
asyncio 在單線程內(nèi)部維護(hù)了 EventLoop 隊(duì)列,然后把需要執(zhí)行異步IO的任務(wù)添加到 EventLoop 隊(duì)列中,至于任務(wù)的完成通過類似回調(diào)的邏輯是實(shí)現(xiàn)后續(xù)的任務(wù)。如果你有 JavaScript的基礎(chǔ)那么理解python的 asyncio 很簡單,關(guān)鍵字、語法以及實(shí)現(xiàn)的原理都極其類似。
import asyncio async def main(): print('Hello ...') await asyncio.sleep(1) print('... World!') # Python 3.7+ asyncio.run(main())
Tornado 是一個(gè)Python web框架和異步網(wǎng)絡(luò)庫,起初由 FriendFeed 開發(fā). 通過使用非阻塞網(wǎng)絡(luò)I/O, Tornado可以支撐上萬級(jí)的連接,處理 長連接, WebSockets ,和其他需要與每個(gè)用戶保持長久連接的應(yīng)用。
下面貼上官方 demo :
import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") def make_app(): return tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": app = make_app() app.listen(8888) tornado.ioloop.IOLoop.current().start()
一個(gè)基于 asyncio 異步的web框架,支持 websocket,不需要寫回掉的代碼、有著豐富的生態(tài)、中間價(jià)等、開箱即用的服務(wù)端與客戶端。
下面貼上官方 demo :
# 客服端代碼 import aiohttp import asyncio async def main(): async with aiohttp.ClientSession() as session: async with session.get('http://python.org') as response: print("Status:", response.status) print("Content-type:", response.headers['content-type']) html = await response.text() print("Body:", html[:15], "...") loop = asyncio.get_event_loop() loop.run_until_complete(main())
# 服務(wù)端代碼 from aiohttp import web async def handle(request): name = request.match_info.get('name', "Anonymous") text = "Hello, " + name return web.Response(text=text) async def wshandle(request): ws = web.WebSocketResponse() await ws.prepare(request) async for msg in ws: if msg.type == web.WSMsgType.text: await ws.send_str("Hello, {}".format(msg.data)) elif msg.type == web.WSMsgType.binary: await ws.send_bytes(msg.data) elif msg.type == web.WSMsgType.close: break return ws app = web.Application() app.add_routes([web.get('/', handle), web.get('/echo', wshandle), web.get('/{name}', handle)]) if __name__ == '__main__': web.run_app(app)
aiohttp的生態(tài):
aiohttp數(shù)據(jù)庫支持:
aiopg PostgreSQL異步支持。
aiomysql MySql 異步支持。
aioredis Redis 異步支持。
asyncpg 另外一個(gè)對(duì) PostgreSQL 異步支持,比 aiopg 效率高,但是 api 不通用。
Sanic 是一個(gè) Python 3.7+ 的基于 asyncio 的 web 服務(wù)器和web框架,目標(biāo)是提供一種簡單的方法來啟動(dòng)和運(yùn)行一個(gè)易于構(gòu)建、擴(kuò)展和終極性能HTTP服務(wù)器,是一個(gè)比較類似 falsk 的異步web框架。
To provide a simple way to get up and running a highly performant HTTP server that is easy to build, to expand, and ultimately to scale.
官方demo:
from sanic import Sanic from sanic.response import json app = Sanic("My Hello, world app") @app.route('/') async def test(request): return json({'hello': 'world'}) if __name__ == '__main__': app.run()
FastAPI 是一個(gè)用于構(gòu)建API的高性能web框架,基于Python3.6+并支持標(biāo)準(zhǔn)的 Python 類型提示。同時(shí)是最快的 Python web框架之一,可與 NodeJS 和 Go 比肩(主要?dú)w功于 Starlette 和 Pydantic)。
from typing import Optional from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: Optional[str] = None): return {"item_id": item_id, "q": q} # 啟動(dòng) uvicorn main:app --reload # pip install uvicorn[standard]
一個(gè)基于asyncio和aiohttp的異步爬蟲框架,目標(biāo)在于讓開發(fā)者編寫爬蟲盡可能地方便快速。國人開發(fā)中文文檔的支持,方便快速的構(gòu)建爬蟲項(xiàng)目,自定義HTML解析工具,快速獲取頁面數(shù)據(jù)。
官方demo:
import asyncio from ruia import Item, TextField, AttrField class HackerNewsItem(Item): target_item = TextField(css_select='tr.athing') title = TextField(css_select='a.storylink') url = AttrField(css_select='a.storylink', attr='href') async def test_item(): url = 'https://news.ycombinator.com/news?p=1' async for item in HackerNewsItem.get_items(url=url): print('{}: {}'.format(item.title, item.url)) if __name__ == '__main__': # Python 3.7 Required. asyncio.run(test_item()) # For Python 3.6 # loop = asyncio.get_event_loop() # loop.run_until_complete(test_item())
隨著 python 社區(qū)對(duì)異步支持的愈發(fā)友好,異步框架的生態(tài)也愈發(fā)完善。Tornado 是我第一個(gè)接觸到的一步框架,現(xiàn)如今伴隨著最快 python web 框架之爭,Tornado也漸漸跌落神壇。但是至于誰是最快的并不重要,重要的是生態(tài),避免重復(fù)造輪子才是重要的。
PS:
最后如果你想使用異步的框架,那么記得所有的IO操作均需要異步操作實(shí)現(xiàn),否則會(huì)大大影響性能。 (比如第三方的短信服務(wù)不能直接使用同步代碼的sdk )
Aiohttp docs
Sanic 中文
Uvloop
Tornado 中文
以上就是python 常用的異步框架匯總整理的詳細(xì)內(nèi)容,更多關(guān)于python異步框架匯總的資料請關(guān)注腳本之家其它相關(guān)文章!
標(biāo)簽:長春 怒江 吉林 安慶 洛陽 泉州 清遠(yuǎn) 岳陽
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《python 常用的異步框架匯總整理》,本文關(guān)鍵詞 python,常用的,常,用的,異步,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。