I have this while loop within one of my Flask routes. The purpose of the function is to retrieve a value from the user and check if that str exists in any filenames within a directory. If true, return "plot_list" and exit function. If false, wait 30 seconds and then check again if that str exists in any filenames within a directory.
@app.route("/data")
def datatable():
selected_project = str(request.args.get('selected_project'))
csv_path = "..\static\csv\dist_drift"
start_time = time.time()
while True:
time.sleep(5)
for fname in os.listdir(csv_path):
if selected_project in fname:
print("{} csv was found in {}".format(selected_project, csv_path))
plot_list = ["basketball.html", "hockey.html"]
return jsonify(plot_list)
else:
current_time = time.time()
print("{} csv not found in {} after waiting {} seconds!".format(selected_project, csv_path,
(current_time - start_time)))
time.sleep(30)
These are the print statements from the function:
Advanced csv was found in \static\csv\dist_drift
None csv not found in \static\csv\dist_drift after waiting 5.001329660415649 seconds!
["basketball.html", "hockey.html"]
None csv not found in \static\csv\dist_drift after waiting 35.00231146812439 seconds!
None csv not found in \static\csv\dist_drift after waiting 65.00326824188232 seconds!
I'm sure this is an easy fix, but I can't figure it out. Any help?
Edit: The problem is that the function isn't exiting even though the str exists in filenames within the directory.
CodePudding user response:
Your return outside the function. Just fix tabs
@app.route("/data")
def datatable():
selected_project = str(request.args.get('selected_Project'))
csv_path = "..\static\csv\dist_drift"
start_time = time.time()
time.sleep(5)
while True:
for fname in os.listdir(csv_path):
if selected_project in fname:
print("{} csv was found in {}".format(selected_project , csv_path))
plot_list = ["basketball.html", "hockey.html"]
print(plot_list)
return jsonify(plot_list)
else:
current_time = time.time()
print("{} csv not found in {} after waiting {} seconds!".format(selected_project , csv_path,
(current_time - start_time)))
time.sleep(30)
CodePudding user response:
you just need to use "break" {break is a simple way to exit a loop} the fixed version of your code is :
@app.route("/data")
def datatable():
selected_project = str(request.args.get('selected_Project'))
csv_path = "..\static\csv\dist_drift"
start_time = time.time()
time.sleep(5)
while True:
for fname in os.listdir(csv_path):
if selected_project in fname:
print("{} csv was found in {}".format(selected_project , csv_path))
plot_list = ["basketball.html", "hockey.html"]
print(plot_list)
break
else:
current_time = time.time()
print("{} csv not found in {} after waiting {} seconds!".format(selected_project , csv_path,
(current_time - start_time)))
time.sleep(30)
return jsonify(plot_list)