异步Python-触发并忘记HTTP请求

时间:2018-09-26 21:37:58

标签: python asynchronous python-asyncio

不确定是否可以实现。我想从脚本中触发HTTP POST请求,但不等待响应。相反,我想立即返回。

我尝试以下方法:

#!/usr/bin/env python3

import asyncio
import aiohttp

async def fire():
    await client.post('http://httpresponder.com/xyz')

async def main():
    asyncio.ensure_future(fire())

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    client = aiohttp.ClientSession(loop=loop)
    loop.run_until_complete(main())

脚本立即返回而没有错误,但是HTTP请求永远不会到达目的地。我可以触发POST请求,但不等待服务器的响应,仅在发送请求后立即终止?

2 个答案:

答案 0 :(得分:1)

使用asyncio可以将简单的装饰器编写为@background。现在,您可以在foo()中编写任何内容,而控制流将不等待其完成。

import asyncio
import time


def background(f):
    from functools import wraps
    @wraps(f)
    def wrapped(*args, **kwargs):
        loop = asyncio.get_event_loop()
        if callable(f):
            return loop.run_in_executor(None, f, *args, **kwargs)
        else:
            raise TypeError('Task must be a callable')    
    return wrapped


@background
def foo():
    time.sleep(1)
    print("foo() completed")


print("Hello")
foo()
print("I didn't wait for foo()")

生产

>>> Hello
>>> I didn't wait for foo()
>>> foo() completed

答案 1 :(得分:0)

have answered的问题很相似。

async def main():
    asyncio.ensure_future(fire())

ensure_future schedules coro execution,但不等待其完成,run_until_complete不等待所有期货的完成。

这应该解决它:

async def main():
    await fire()
相关问题