python web 异步 asyncio

1、asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持

2、通过asyncio模块中对EventLoop的引用,然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO。

import threading
import asyncio

@asyncio.coroutine #把一个生成器标记为coroutine类型
def hello():
    print('Hello world! (%s)' % threading.currentThread())
    yield from asyncio.sleep(1) #generator 且是coroutine 类型
    #yield from语法可以让我们方便地调用另一个generator。由于asyncio.sleep()也是一个coroutine 
    #所以线程不会等待asyncio.sleep(),而是直接中断并执行下一个消息循环,
    #是不是这个coroutine没有放入到eventloop 在此中断不执行???
    print('Hello again! (%s)' % threading.currentThread())

loop = asyncio.get_event_loop()
#把coroutine扔到eventloop执行 #两个coroutine是由同一个线程并发执行的
tasks = [hello(), hello()]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()


Python 3.5开始引入了新的语法asyncawait 

@asyncio.coroutine替换为async

yield from替换为await

3、aiohttp

asyncio实现了TCP、UDP、SSL等协议,aiohttp则是基于asyncio实现的HTTP框架

asyncio可以实现单线程并发IO操作。如果仅用在客户端,发挥的威力不大。如果把asyncio用在服务器端,例如Web服务器,由于HTTP连接就是IO操作,因此可以用单线程+coroutine实现多用户的高并发支持

import asyncio

from aiohttp import web

async def index(request):
    await asyncio.sleep(0.5) # 此处故意写一个 asyncio.sleep 实现单线程、多用户?
    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()
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值