【问题标题】:If I have two routes in flask pointing towards the same url, how does flask decide what functions to run?如果我在烧瓶中有两条路线指向同一个 url,烧瓶如何决定要运行哪些功能?
【发布时间】:2020-03-22 07:05:37
【问题描述】:

我有一个简单的烧瓶应用程序,我从输入页面获取图像文件路径,然后切换到显示图像的输出页面。我的应用程序正常运行并设法访问我保存的文件并将它们显示在新页面上,但我意识到我有两条指向同一个地方的路线。我的代码如下所示:

@app.route('/')
def main_page():
    return render_template('input_receiver.html')

@app.route('/', methods = ['POST', 'GET'])
def get_input():
    if request.method == 'POST':
        user = request.form['nm']
        return redirect(url_for('success', name=user))

这两个函数指向我最初的 localhost:5000 页面,第一个函数呈现一个带有文本字段输入和按钮的 html 文件。为了连接到实际的烧瓶脚本,它在表单标记中包含以下行:

<form action = "http://localhost:5000" method = "post">

('nm' 是初始 HTML 页面上的文本字段输入)

第二个函数接收本地图像文件路径的用户输入,并在他们按下显示他们输入的图片的按钮后将它们重定向到 HTML 文件。这是通过以下函数完成的。

@app.route('/<name>')
def success(name):
    return render_template('popup.html', picture_path = "/static/" + name)

两条路由都指向初始的 localhost:5000 页面,那么flask 是如何处理执行的呢?如果这被认为是创建此类功能的坏方法,那么更好的方法是什么?

【问题讨论】:

    标签: python flask


    【解决方案1】:

    您可以将GETPOST 放在同一个route 下的同一个方法中。

    @app.route('/', methods = ['POST', 'GET'])
    def get_input():
        if request.method == 'POST':
            user = request.form['nm']
            return redirect(url_for('success', name=user))
        return render_template('input_receiver.html')
    

    您已经为路由/ - 方法get_input() 提供了GETPOST 的方法,因此您可以完全删除另一个方法-main_page

    您的GETPOST 请求都可以通过这一种方法处理。

    【讨论】:

      猜你喜欢
      • 2013-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2016-08-26
      • 1970-01-01
      相关资源
      最近更新 更多