aiohttp
来源:互联网 发布:mac显示.m2文件夹 编辑:程序博客网 时间:2024/06/01 19:24
asyncio可以实现单线程并发IO操作。如果仅用在客户端,发挥的威力不大。如果把asyncio用在服务器端,例如Web服务器,由于HTTP连接就是IO操作,因此可以用单线程+coroutine实现多用户的高并发支持。
asyncio实现了TCP、UDP、SSL等协议,aiohttp则是基于asyncio实现的HTTP框架。
我们先安装aiohttp:
pip install aiohttp
然后编写一个HTTP服务器,分别处理以下URL:
/ - 首页返回b'<h1>Index</h1>';/hello/{name} - 根据URL参数返回文本hello, %s!。
代码如下:
import asynciofrom aiohttp import webasync 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...') return srvloop = asyncio.get_event_loop()loop.run_until_complete(init(loop))loop.run_forever()
注意aiohttp的初始化函数init()也是一个coroutine,loop.create_server()则利用asyncio创建TCP服务。
阅读全文
0 0
- aiohttp
- aiohttp
- aiohttp
- python aiohttp
- aiohttp 简易使用教程
- aiohttp,asyncio, RunTimeError
- Grequests VS aiohttp+asyncio
- python install aiohttp
- python学习——aiohttp
- JWT Authorization in Python aiohttp
- python aiohttp简易使用教程
- Python aiohttp后台导出excel文件
- python的异步IO(asyncio aiohttp)
- asyncio/aiohttp 的协程爬虫
- 使用 aiohttp 和 asyncio 进行异步请求
- asyncio/aiohttp 异步爬取douban
- 异步爬虫: async/await 与 aiohttp的使用,以及例子
- 使用python-aiohttp搭建微信公众平台
- 507. Perfect Number
- HALCON学第1天
- Python机器学习ufunc函数
- 单链表面试常考
- Tensorflow之路(一)tensorflow更新版本
- aiohttp
- 解决mac-osx10.11下无法安装wxPython2.8-osx-unicode-2.8.12.1的问题
- 存储设备管理与分区
- struts2学习_第二天
- 数据分析——以斗鱼为实例解析requests库与scrapy框架爬虫技术
- Oracle GoldenGate介绍
- 记录我发现的第一个关于 Google 的 Bug
- Java 命令找不到或无法加载主类
- 初识Matlab面向对象编程