0

I'm trying to achieve a mechanism to "fire and Forget" My request and return to the call function, but my function always waits for the responses.

import requests

class Res():
    def process_data(self, data):
        # some data process
        plan = {'data':'test'}
        # Fire and Forget i dont care about the return value
        asyncio.run(self.fire(plan))

        # Im tryting to return the response before the response from the above call
        response = {'rid': '12345'}
        return response


    async def fire(self,message):
        print("async_foo done")
        payload = json.dumps(message, indent=4, default=lambda x: x.__dict__)
        headers = {'content-type': 'application/json'}
        async with aiohttp.ClientSession() as session:
            async with session.post(RUNTIME_URL, data=payload, headers=headers) as resp:
                print(resp.status)
                print(await resp.text())

Can some one help, im not sure what im missing here.

DonOfDen
  • 3,968
  • 11
  • 62
  • 112
  • Use asyncio.create_task instead of asyncio.run. – Paul Cornelius Mar 06 '20 at 12:12
  • ```RuntimeError: no running event loop``` errir :( – DonOfDen Mar 06 '20 at 12:22
  • You always have to have a running event loop in order to execute a coroutine. Perhaps what you want is threads rather than asyncio. You can never just literally "fire and forget" because something has to keep your program running until the thing you fired is finished executing - otherwise why have a program at all? The event loop (often the last line in your program) is the thing that keeps running until.it is stopped. BTW I think the question should not have been closed. – Paul Cornelius Mar 06 '20 at 13:26
  • So what should i try now a thread? @PaulCornelius – DonOfDen Mar 06 '20 at 13:40
  • You say you don't want "fire" to run as part of the main execution sequence of your program logic. You want it to run "somewhere else" outside of the main flow of your program - almost like a separate program. The question is where will it run? It can be in a separate thread, or a separate process, or in an event loop coroutine. Those are the only possibilities I know of. The choice is up to you. – Paul Cornelius Mar 06 '20 at 20:04

0 Answers0