【学习笔记】Python基础-aiohttp

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>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

法迪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值