Python post request display message if response taking longer than x seconds

Viewed 14

I have the following python code that fetches data from a remote json file. The processing of the remote json file can sometimes be quick or sometimes take a little while. So I put the please wait print message before the post request. This works fine. However, I find that for the requests that are quick, the please wait is pointless. Is there a way I can display the please wait message if request is taking longer than x seconds?

try:
    print("Please wait")
    r = requests.post(url = "http://localhost/test.php")
    r_data = r.json()
1 Answers

you can do it using multiple threads as follows:

import threading
from urllib import request
from asyncio import sleep


def th():
    sleep(2) # if download takes more than 2 seconds
    if not isDone:
        print("Please wait...")


dl_thread = threading.Thread(target=th) # create new thread that executes function th when the thread is started
dl_thread.start() # start the thread

isDone = False # variable to track the request status
r = request.post(url="http://localhost/test.php")
isDone = True

r_data = r.json()
Related