python aiohttp_aiohttp
asyncio可以實現單線程并發IO操作。如果僅用在客戶端,發揮的威力不大。如果把asyncio用在服務器端,例如Web服務器,由于HTTP連接就是IO操作,因此可以用單線程+coroutine實現多用戶的高并發支持。
asyncio實現了TCP、UDP、SSL等協議,aiohttp則是基于asyncio實現的HTTP框架。
我們先安裝aiohttp:
pip install aiohttp
然后編寫一個HTTP服務器,分別處理以下URL:
/ - 首頁返回b'
Index
';/hello/{name} - 根據URL參數返回文本hello, %s!。
代碼如下:
import asyncio
from aiohttp import web
async def index(request):
await asyncio.sleep(0.5)
return web.Response(body=b'
Index
')async def hello(request):
await asyncio.sleep(0.5)
text = '
hello, %s!
' % request.match_info['name']return web.Response(body=text.encode('utf-8'))
async def init(loop):
app = web.Application(loop=loop)
app.router.add_route('GET', '/', index)
app.router.add_route('GET', '/hello/{name}', hello)
srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000)
print('Server started at http://127.0.0.1:8000...')
return srv
loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()
注意aiohttp的初始化函數init()也是一個coroutine,loop.create_server()則利用asyncio創建TCP服務。
參考源碼
總結
以上是生活随笔為你收集整理的python aiohttp_aiohttp的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 英特尔核芯显卡控制面板没有了_「有趣」第
- 下一篇: 在python中定义类时、运算符重载_p