Servicio http asíncrono de python - asyncio

esperar/async

esperar

Un objeto awaitable ( awaitable object) debe conectarse después de await Hay tres tipos de objetos awaitable: rutinas coroutine, tareas Tasky objetos futuros Future.

asíncrono

async se usa para modificar la función, y la función modificada por async devuelve un objeto coroutine. Llamar a la función asíncrona directamente no ejecutará la función, puede usar await o asyncio.run para ejecutar realmente la función asíncrona.

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!

asíncio

bucle de eventos

Bucle de eventos, todos los objetos en espera se ejecutan en el bucle de tiempo, un objeto en espera solo puede ejecutarse en un bucle de eventos y un bucle de eventos puede contener varios objetos en espera.

asyncio.get_event_loop()

Obtenga el bucle de eventos actual, cree uno si no existe y regrese.

asincio.nuevo_event_loop()

Crear un nuevo bucle de eventos y regresar

asyncio.get_running_loop()

Volver al bucle de eventos en ejecución

ejemplo

Un servicio http escucha en dos puertos

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

おすすめ

転載: blog.csdn.net/chinesesexyman/article/details/117589299
おすすめ