Issue
I've been scouring the web to an answer to this question but I can't seem to find an actual answer or maybe i'm just missing it.
I'm trying to fire off a post request to start another microservice and I don't care what response comes back as that goes to a different part of my architecture
Once the request is sent I want to essentially continue the code a return this random json to where the function is called. For some reason whenever I use asyncio.run() it starts the send_requests() function but waits for it to respond before continuing.
Which is how async works i this case I think. But i'm unsure how to continue and exit the function before waiting for a response
Here's the pseudo code
Class DummyClass:
def do_something():
"doing something...."
asyncio.run(send_requests)
return "random string"
async def send_request():
try:
requests.post("send to url")
except:
raise Issue
I can use a decorator
def fire_and_forget(f):
@wraps(f)
def wrapped(*args, **kwargs):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
if callable(f):
return loop.run_in_executor(None, f, *args, **kwargs)
else:
raise TypeError("Task must be a callable")
return wrapped
which works fine but just wondering if we can do it without the decorator! I think I might be slightly misunderstanding asyncio
Thanks for any help.
I've been looking at "Fire and forget" python async/await but can't seem to work
Solution
Your code is essentially threading.Thread(target=requests.post, args=("send to url",)).start()
with lots of extra steps. And I think that's what you need here.
If you want to make it truly async (say you want to send hundreds of these without creating countless threads), you need to create async tasks and use await
on a POST using an async library (e.g. httpx instead of requests). Those tasks then need to run in an event loop, which itself should be launched in a separate thread if you don't want the loop to block your main thread.
You seem to have some misconceptions about async: There's no async without event loop, and an event loop does not spawn in a separate thread. It does not jump around between arbitrary code, but only between Awaitables at predefined locations (await
). If you can't await
where you want your code to jump out, it's not async-compatible.
Answered By - Matthias Huschle
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.