Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 937
Sumanth Shetty Avatar asked Oct 28 '19 09:10

Sumanth Shetty


People also ask

How do I send a POST request without waiting for response?

You cannot just send data without receiving an answer with HTTP. HTTP always goes request -> response. Even if the response is just very short (like a simple 200 with no text), there needs to be a response. And every HTTP socket will wait for that response.

How to send POST request from Python?

The post() method sends a POST request to the specified url. The post() method is used when you want to send some data to the server.

How do you make a GET request wait in Python?

There are two ways: use the wait argument in render to add a wait time in seconds before the javascript is rendered and use the sleep argument to add a wait in seconds time after the js has rendered. Both arguments only accept integer values. Example: response. html.

What does request POST do?

By design, the POST request method requests that a web server accept the data enclosed in the body of the request message, most likely for storing it. It is often used when uploading a file or when submitting a completed web form. In contrast, the HTTP GET request method retrieves information from the server.


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.

like image 100
Ramazan Polat Avatar answered Nov 15 '22 06:11

Ramazan Polat