Search code examples
pythonhttppython-requestspython-multithreading

Threaded HTTP post via requests without waiting for request to go through


My program is sending out an http post every 250ms or so and I want it to keep running while the request goes through. Essentially I am looking for something like a file and forget system that just sends off the request (perhaps in a different thread) and keeps on going without waiting for a response from the server.

The program looks something like:

while True:
    value_to_send = some_function()
    x = requests.post(url, json = myjson) # this json has the updated value_to_send in it 

Solution

  • You could use threads and simply dont wait for them to finish:

    from threading import Thread
    import time
    
    def request():
        # value_to_send = some_function()
        # x = requests.post(url, json = myjson)
        print('started')
        time.sleep(.5)
        print("request done!")
    
    
    def main():
        while True:
            t = Thread(target=request)
            t.start()
            time.sleep(.25)
    
    main()
    

    Output:

    started
    started
    request done!
    started
    request done!
    started
    request done!
    ...