python - Flask 单击按钮即可转到新页面

标签 python python-3.x flask

我有一个带有索引页面的小型 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/

相关文章:

python - 将Python字典中的元素移动到另一个索引

python - 将多个值存储到 mysql 数据库中的单个字段中以保留 Django 中的顺序

python - window : OpenCV is installed but getting "Unable to import cv2" error in Python

python - 通用换行模式是否应该是 Python 2.7 中 open() 的默认行为?

python - 从转储数据中排除 admin.logenty

python - 了解两个不同大小的矩阵的 np.corrcoef 输出

python-3.x - Keras 模型属性错误 : 'str' object has no attribute 'call'

python - 错误: 502 bad gateway in flask app on nginx and uwsgi

python - 带 flask 的服务图像

python - 在 flask socketio 后台任务中访问应用上下文