10

Hi i am new to python development.

i have to make multiple push in very short amount of time(seconds preferably).

currently i am using request package's post method to post the data into an API . But , by default request method waits for the response from the API.

requests.post(url, json=data, headers=headers)

Is there any other way that i can post the data into API in asynchronous way ?

Thank you

Sumanth Shetty
  • 587
  • 1
  • 8
  • 19

1 Answers1

20

If you are not interested in response from the server(fire and forget) then you can use an async library for this. But I must warn you, you cannot mix sync and async code(actually you can but it's not worth dealing with it) so most of your codes must be changed.

Another approach is using threads, they can call the url seperately wait for the response without affecting rest of your code.

Something like this will help:

def request_task(url, json, headers):
    requests.post(url, json=data, headers=headers)


def fire_and_forget(url, json, headers):
    threading.Thread(target=request_task, args=(url, json, headers)).start()

...

fire_and_forget(url, json=data, headers=headers)

Brief info about threads

Threads are seperate flow of execution. Multiple threads run concurrently so when a thread is started it runs seperately from current execution. After starting a thread, your program just continue to execute next instructions while the instructions of thread also executes concurrently. For more info, I recommend realpython introduction to threads.

ramazan polat
  • 7,111
  • 1
  • 48
  • 76
  • ,Could you please explain me the use of threading.Thread there ? – Sumanth Shetty Oct 28 '19 at 09:22
  • @SumanthShetty it's not easy to explain threads in an answer, you should follow the link I provided in the answer to get a better understanding of it. – ramazan polat Oct 28 '19 at 11:17
  • @SumanthShetty, if this solved your issue, please consider to click the green checkbox to make it an accepted answer, so others know it works. – ramazan polat Oct 29 '19 at 21:46
  • 3
    Thank you so much for not just recommending Celery as a silver bullet like everybody else and for providing such a clean and simple example. This was the perfect solution for my use case. – Ariel Sep 10 '21 at 14:54
  • 1
    this is a simple solution, no grequests, no asyncio, no celery or rabbitmq, thanks. – DeyaEldeen Nov 22 '21 at 19:38