python学习——aiohttp
2016-07-20 09:14
465 查看
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 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...') 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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法