Flask Multithreading Issue Not Executing Properly Long Load Time

Question:

Basically, In my flask application, I have a function. In this function, I am sending a request which takes 20 seconds to complete. So I added multithreading to solve this. But for some reason, it is not threading properly and the page load time is 20 seconds when it should be quick.

from  flask import Flask
app = Flask(__name__, template_folder='')
class NewThreadedTask(threading.Thread):
     def __init__(self):
         super(NewThreadedTask, self).__init__()
def run(uid):
    requests.get("http://192.168.1.9:5001/run?old="+uid)
@app.route('/get')
def get(uid):
    uid="Player1"
    threading.Thread(target=run(uid)).start()
    return uid+" banned"
app.run(host='0.0.0.0', port=80)
Asked By: big boss

||

Answers:

You are first running the function, by calling it with the expression run(uid), and just when it returns, the call with the return value of it is made to create a new thread (which makes no sense, since it has no return value).

When creating threads in Python, the target function is called without parentheses – so that it will be called in the new thread. Arguments to the function can be passed to the Thread creation in the args argument.

from  flask import Flask
app = Flask(__name__, template_folder='')
# no need for a custom thread class.

def run(uid):
    requests.get("http://192.168.1.9:5001/run?old="+uid)
@app.route('/get')
def get(uid):
    uid="Player1"
    # create a new thread with `run` as  a target, and `uid` as its argument:
    threading.Thread(target=run, args=(uid,)).start()
    # ideally you should return status code HTTP 202 (accepted) here
    return uid+" banned"
app.run(host='0.0.0.0', port=80)

non related async programing info

Note that this is in contrast when coding with async code: when a function is created with async def, it should be called with the usual parentheses syntax: Python will imediately return a co-routine with the information it needs to run that task. One than can either await this co-routine (it is executed sequentially in the current task, and the code has to wait all the time it takes), or submitted as a task to the asyncio loop (at the point it will run roughly equivalent to the way threads run).

(I included this bit here because by seeing alternating examples of threading and async code in the wild, one might get confused)

Answered By: jsbueno
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.