在 Flask 中,如何在单击按钮时生成动态 URL?

2024-05-01

例如,现在如果我在表单元素中有两个按钮,当您单击其中任一按钮时,您将被定向到相应的配置文件。

<form action="{{ url_for('getProfile') }}" method="post">
    <button type="submit" name="submit" value="profile1"> View Profile</button>
    <button type="submit" name="submit" value="profile2"> View Profile</button>
</form>

在我的 apprunner.py 中,我有

 @app.route('/profile', methods=['POST'])
 def getProfile():
       if request.form['submit'] = 'profile1':
            return render_template("profile1.html")
       else if request.form['submit'] = 'profile2':
            return render_template("profile2.html")

但是,我的问题是,当我单击任一按钮时,网址始终会类似于“127.0.0.1:5000/profile”。但是,我希望它看起来像“http://127.0.0.1:5000/profile1 http://127.0.0.1:5000/profile1" or "http://127.0.0.1:5000/profile2 http://127.0.0.1:5000/profile2".

我一直在寻找有关如何在线生成动态 URL 的解决方案,但它们都不适用于按钮单击。

提前致谢!


@app.route('/profile<int:user>')                                                                                                   
def profile(user):                                                                                                             
    print(user)

您可以在 REPL 上测试它:

import flask
app = flask.Flask(__name__)

@app.route('/profile<int:user>')
def profile(user):
    print(user)

ctx = app.test_request_context()
ctx.push()

flask.url_for('.profile', user=1)
'/profile1'

EDIT:

你如何通过user新路线的参数取决于您的需要。如果您需要硬编码路线profile1 and profile2你可以通过user=1 and user=2分别。如果您想以编程方式生成这些链接,取决于这些配置文件的存储方式。

否则你可以redirect代替render_template,到url_for与请求对象中解析的元素。这意味着有两条路线

@app.route('/profile<int:user>')
def profile_pretty(user):
    print(user)

@app.route('/profile', methods=['POST'])
def getProfile():
      if request.form['submit'] = 'profile1':
           return redirect(url_for('.profile_pretty', user=1))
       else if request.form['submit'] = 'profile2':
            return redirect(url_for('.profile_pretty', user=2))

caveat:这会让你的路由看起来像你想要的那样,但是这是低效的,因为它每次都会生成一个新的请求,只是为了让你的网址成为你想要的方式。此时可以安全地询问why您是否想要为静态内容动态生成路由。


正如中所解释的http://exploreflask.com/en/latest/views.html#url-converters http://exploreflask.com/en/latest/views.html#url-converters

当您在 Flask 中定义路由时,您可以指定其中将被转换为 Python 变量并传递给视图函数的部分。

@app.route('/user/<username>')
def profile(username):
    pass

URL 标记部分中的任何内容都将作为用户名参数传递到视图。您还可以指定一个转换器来在将变量传递到视图之前对其进行过滤。

@app.route('/user/id/<int:user_id>')
def profile(user_id):
    pass

在此代码块中,URLhttp://myapp.com/user/id/Q29kZUxlc3NvbiEh http://myapp.com/user/id/Q29kZUxlc3NvbiEh将返回 404 状态代码 – 未找到。这是因为 URL 中应该是整数的部分实际上是字符串。

我们还可以有第二个视图来查找字符串。这将被称为 /user/id/Q29kZUxlc3NvbiEh/ 而第一个将被称为 /user/id/124。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Flask 中,如何在单击按钮时生成动态 URL? 的相关文章

随机推荐