国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

python 常用的異步框架匯總整理

瀏覽:40日期:2022-06-16 11:41:45
目錄正文開(kāi)始1. Tornado2. Aiohttp3.Sanic4. FastAPI5. Ruia總結(jié)參考資料正文開(kāi)始

asyncio 是 Python 3.4版本引入的標(biāo)準(zhǔn)庫(kù),直接內(nèi)置了對(duì)異步IO的支持。

asyncio 在單線程內(nèi)部維護(hù)了 EventLoop 隊(duì)列,然后把需要執(zhí)行異步IO的任務(wù)添加到 EventLoop 隊(duì)列中,至于任務(wù)的完成通過(guò)類似回調(diào)的邏輯是實(shí)現(xiàn)后續(xù)的任務(wù)。如果你有 JavaScript的基礎(chǔ)那么理解python的 asyncio 很簡(jiǎn)單,關(guān)鍵字、語(yǔ)法以及實(shí)現(xiàn)的原理都極其類似。

import asyncioasync def main(): print(’Hello ...’) await asyncio.sleep(1) print(’... World!’)# Python 3.7+asyncio.run(main())1. Tornado

Tornado 是一個(gè)Python web框架和異步網(wǎng)絡(luò)庫(kù),起初由 FriendFeed 開(kāi)發(fā). 通過(guò)使用非阻塞網(wǎng)絡(luò)I/O, Tornado可以支撐上萬(wàn)級(jí)的連接,處理 長(zhǎng)連接, WebSockets ,和其他需要與每個(gè)用戶保持長(zhǎng)久連接的應(yīng)用。

下面貼上官方 demo :

import tornado.ioloopimport tornado.webclass 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()2. Aiohttp

一個(gè)基于 asyncio 異步的web框架,支持 websocket,不需要寫回掉的代碼、有著豐富的生態(tài)、中間價(jià)等、開(kāi)箱即用的服務(wù)端與客戶端。

下面貼上官方 demo :

# 客服端代碼import aiohttpimport asyncioasync 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 webasync 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 wsapp = 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-session 為 aiohttp 服務(wù)提供 sessions支持,同時(shí)支持?jǐn)?shù)據(jù)持久化數(shù)據(jù)庫(kù)。 aiohttp-debugtoolbar 為 aiohttp 提供調(diào)試的工具(記錄 asyncio 異常的堆棧信息)。 aiohttp-security 為aiohttp提供認(rèn)證以及權(quán)限相關(guān)的插件。 aiohttp-devtools aiohttp開(kāi)發(fā)工具,提供開(kāi)發(fā)環(huán)境的部署、靜態(tài)資源的代理。 aiohttp-cors CORS 跨域認(rèn)證支持。 aiohttp-sse 服務(wù)端事件的支持(一種服務(wù)端推送消息的服務(wù))。 pytest-aiohttp pytest 測(cè)試框架的支持。 aiohttp-mako Mako 服務(wù)端模板渲染的支持。 aiohttp-jinja2 Jinja2 服務(wù)端模板渲染的支持(大名鼎鼎的flask的渲染引擎)。 aiozipkin 分布式系統(tǒng)中對(duì)服務(wù)追蹤,為微服務(wù)中延時(shí)問(wèn)題提供數(shù)據(jù)支持。

aiohttp數(shù)據(jù)庫(kù)支持:

aiopg PostgreSQL異步支持。aiomysql MySql 異步支持。aioredis Redis 異步支持。asyncpg 另外一個(gè)對(duì) PostgreSQL 異步支持,比 aiopg 效率高,但是 api 不通用。

3.Sanic

Sanic 是一個(gè) Python 3.7+ 的基于 asyncio 的 web 服務(wù)器和web框架,目標(biāo)是提供一種簡(jiǎn)單的方法來(lái)啟動(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 Sanicfrom sanic.response import jsonapp = Sanic('My Hello, world app')@app.route(’/’)async def test(request): return json({’hello’: ’world’})if __name__ == ’__main__’: app.run()4. FastAPI

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 Optionalfrom fastapi import FastAPIapp = 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]5. Ruia

一個(gè)基于asyncio和aiohttp的異步爬蟲(chóng)框架,目標(biāo)在于讓開(kāi)發(fā)者編寫爬蟲(chóng)盡可能地方便快速。國(guó)人開(kāi)發(fā)中文文檔的支持,方便快速的構(gòu)建爬蟲(chóng)項(xiàng)目,自定義HTML解析工具,快速獲取頁(yè)面數(shù)據(jù)。

官方demo:

import asynciofrom ruia import Item, TextField, AttrFieldclass 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())總結(jié)

隨著 python 社區(qū)對(duì)異步支持的愈發(fā)友好,異步框架的生態(tài)也愈發(fā)完善。Tornado 是我第一個(gè)接觸到的一步框架,現(xiàn)如今伴隨著最快 python web 框架之爭(zhēng),Tornado也漸漸跌落神壇。但是至于誰(shuí)是最快的并不重要,重要的是生態(tài),避免重復(fù)造輪子才是重要的。

PS:

我記得之前了解 Sanic 的時(shí)候它還是基于 aiohttp 開(kāi)發(fā)的 web 框架,現(xiàn)如今已經(jīng)重構(gòu)了大部分代碼,核心組件也都自己實(shí)現(xiàn)。 tornado 雖然語(yǔ)法過(guò)時(shí)了,但是應(yīng)該是最成熟、最早以及文檔最多的一個(gè)異步框架。 之前用tornado的時(shí)候還需要造關(guān)于異步操作的輪子,現(xiàn)如今生態(tài)日趨完善。

最后如果你想使用異步的框架,那么記得所有的IO操作均需要異步操作實(shí)現(xiàn),否則會(huì)大大影響性能。 (比如第三方的短信服務(wù)不能直接使用同步代碼的sdk )

參考資料

Aiohttp docs

Sanic 中文

Uvloop

Tornado 中文

以上就是python 常用的異步框架匯總整理的詳細(xì)內(nèi)容,更多關(guān)于python異步框架匯總的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 邵阳市| 三台县| 双桥区| 长沙市| 淮阳县| 红桥区| 香格里拉县| 宜宾市| 隆德县| 松潘县| 阜阳市| 靖西县| 黔江区| 元谋县| 平遥县| 湛江市| 绥化市| 凯里市| 新巴尔虎左旗| 樟树市| 襄城县| 修文县| 盱眙县| 枣强县| 城口县| 长寿区| 博兴县| 霍邱县| 无为县| 大连市| 濉溪县| 荣成市| 开阳县| 沙河市| 南昌县| 仁布县| 海城市| 博湖县| 天峨县| 宁都县| 天全县|