How to work with request.post() method without waiting for response

Viewed 12416

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

1 Answers

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.

Related