我有一个带有索引页面的小型 flask 应用程序,用户可以从下拉菜单中选择目录。一旦用户做出选择并单击网页上的“提交”,我想将他们发送到一个新页面,其中包含特定于该目录的信息。
我试图通过在从索引页面获取输入后简单地调用该函数来加载新页面。我的问题是,单击网页上的“提交”会重新加载相同的索引页面。
flask 代码:
app = Flask(__name__)
dirname = os.path.dirname(sys.argv[0])
run_path = ""
@app.route("/", methods = ["GET", "POST"])
def index():
dir_loc = "/Users/kregan1/Documents"
dir_data = list(os.listdir(dir_loc))
if request.method == "POST":
run_dir = request.form.get("run_list")
run_path = dir_loc + "/" + run_dir
run(run_path)
return render_template('index.html', data = dir_data)
@app.route("/run", methods = ["GET", "POST"])
def run(run_path):
if os.path.isdir(run_path) == True:
file_lists = []
for f in os.listdir(run_path):
if f.startswith("pattern"):
file_lists.append(run_path + "/" + f)
projects = []
for fl in file_lists:
with open(fl) as f:
for row in f:
if row.split(",")[0] not in projects:
projects.append(row.split(",")[0])
else:
projects = ["a","b","c"]
return render_template('run.html', run = run_path, proj_data = projects )
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css') }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="{{url_for('static', filename='asp_javascript.js')}}"></script>
</head>
<body>
<h2>Packaging Tool - Index</h2>
<p>Select Run:</p>
<form action="{{ url_for("index") }}" method="post">
<select name="run_list">
{% for d in data %}
<option>{{d}}</option>
{% endfor %}
</select>
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
最佳答案
您可以使用redirect(...)
,而不仅仅是调用该函数。
from flask import redirect
...
if request.method == "POST":
run_dir = request.form.get("run_list")
run_path = dir_loc + "/" + run_dir
return redirect(url_for('run', run_path=run_path))
@app.route("/run/<run_path>", methods = ["GET", "POST"])
def run(run_path):
if os.path.isdir(run_path) == True:
...
关于python - Flask 单击按钮即可转到新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71055372/