Reputation:
I have a web application route in flask. The route is supposed to give the user an analysis of their data after 30 minutes. To do this, they initiate the route. This triggers an API request that takes gets their initial data. The route then sleeps for 30 minutes, and then triggers the same exact API response. The initial data is subtracted from the final data and result the data that is 'attained' in that 30 minutes and is upserted to a database. An example of how it would look is below. I would like my users to be able to use the other features of the website, or more importantly even initiate another instance of this function, while this runs. My question is: is this an async problem or a multithread problem and why? I would like to note that my question is more conceptual then about the actual code.
@app.route("/data/", methods=['GET', 'POST', 'UPDATE'])
@login_required
def data():
Url = "https://data-api.com"
payload={}
headers = {
'Authorization': AUTH
}
response = requests.request("GET", Url, headers=headers, data=payload)
data_json = json.loads(response.text)
data1_init = data_json["a"]["b"]["c"]
data2_init = data_json["e"]["f"]["g"]
data3_init = data_json["h"]["i"]["j"]
sleep(1800)
Url = "https://data-api.com"
payload={}
headers = {
'Authorization': AUTH
}
response = requests.request("GET", Url, headers=headers, data=payload)
data_json = json.loads(response.text)
data1_final = data_json["a"]["b"]["c"]
data2_final = data_json["e"]["f"]["g"]
data3_final = data_json["h"]["i"]["j"]
data1 = data1_final - data1_initial
data2 = data2_final - data2_initial
data3 = data3_final - data3_initial
data_info = DBModel(data1=data1, data2=data2, data3=data3)
db.session.commit()
return render_template('loading.html')
Upvotes: 1
Views: 1606
Reputation: 33
def run_func():
data = { 'some': 'data', 'any': 'data' }
thr = Thread(target= *your_function*, args=[app, data])
thr.start()
return thr
You can use threading. Put your function name in place of "your_function", pass the function parameters in args and there you go. Just call the run_func() wherever you want to execute and it starts running in background in an other thread.
Upvotes: 2