您的位置:首页 > 大数据 > 人工智能

【学习笔记】Python基础-aiohttp

2017-12-26 19:50 453 查看
aiohttp 的初始化函数init()也是一个coroutine,loop.create_server()则利用asyncio创建TCP服务

具体 廖雪峰老师的

https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014320981492785ba33cc96c524223b2ea4e444077708d000

安装 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()


运行结果

浏览器输入:

http://127.0.0.1:8000/hello/王大锤

<h1>hello, 王大锤!</h1>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python aiohttp web-Respon