【學習筆記】Python基礎-aiohttp
阿新 • • 發佈:2019-01-24
aiohttp 的初始化函式init()也是一個coroutine,loop.create_server()則利用asyncio建立TCP服務
安裝 aiohttp
安裝命令: pip install aiohttp
D:\PythonProject\sustudy>pip install aiohttp
Collecting aiohttp
Downloading aiohttp-2.3.6-cp36-cp36m-win_amd64.whl (370kB)
100% |████████████████████████████████| 378kB 701kB/s
Collecting yarl>= 0.11 (from aiohttp)
Downloading yarl-0.16.0-cp36-cp36m-win_amd64.whl (85kB)
100% |████████████████████████████████| 92kB 383kB/s
Collecting multidict>=3.0.0 (from aiohttp)
Downloading multidict-3.3.2-cp36-cp36m-win_amd64.whl (185kB)
100% |████████████████████████████████| 194kB 175kB/s
Collecting async-timeout >=1.2.0 (from aiohttp)
Downloading async_timeout-2.0.0-py3-none-any.whl
Requirement already satisfied: chardet in c:\programdata\anaconda3\lib\site-packages (from aiohttp)
Installing collected packages: multidict, yarl, async-timeout, aiohttp
Successfully installed aiohttp-2.3.6 async-timeout-2.0.0 multidict- 3.3.2 yarl-0.16.0
執行示例
# main.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Python基礎-Web 服務端 aiohttp
import asyncio
from aiohttp import web
async def index(request):
await asyncio.sleep(0.5)
return web.Response(body = b'<h1>Index</h1>')
async def hello(request):
await asyncio.sleep(0.5)
text = '<h1>hello, %s!</h1>' % 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...')
loop = asyncio.get_event_loop()
loop.run_until_complete(init(loop))
loop.run_forever()
執行結果
<h1>hello, 王大錘!</h1>