目录
await/async
await
await后必须接一个可等待对象(awaitable object
),可等待对象有3类:协程coroutine
、任务Task
、未来对象Future
。
async
async用来修饰函数,被async修饰的函数返回一个协程对象。直接调用async函数不会执行函数,可以用await或asyncio.run等方式来真正执行async函数。
import asyncio
async def foo():
print('This is a async function!')
async def main():
await foo()
if __name__ == '__main__':
# asyncio.run
obj = foo()
asyncio.run(obj)
# await
asyncio.run(main())
>>> This is a async function!
>>> This is a async function!
asyncio
event loop
事件循环,所有的可等待对象都运行在时间循环里,一个可等待对象只能运行在一个事件循环里,一个事件循环可包含多个可等待对象。
asyncio.get_event_loop()
获取当前事件循环,不存在则创建一个并返回。
asyncio.new_event_loop()
新建事件循环并返回
asyncio.get_running_loop()
返回正在运行的事件循环
example
一个http服务监听两个端口
import asyncio
from aiohttp import web
async def hello(request):
print(request)
return web.Response(text='hello')
async def goodbye(request):
print(request)
return web.Response(text='goodbye')
async def foo1():
app = web.Application()
routes = [web.get('/hello', hello)]
app.add_routes(routes)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, host='192.168.30.5', port=12138)
await site.start()
async def foo2():
app = web.Application()
routes = [web.get('/goodbye', goodbye)]
app.add_routes(routes)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, host='192.168.30.5', port=12139)
await site.start()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.create_task(foo1())
loop.create_task(foo2())
loop.run_forever()
curl 'http://192.168.30.5:12139/goodbye'
goodbye
curl 'http://192.168.30.5:12138/hello'
hello