问题描述
例如,现在,如果我在表单元素中有两个按钮,则单击它们中的任何一个时,您将被定向到相应的配置文件.
For example, now if I have two buttons in a form element, when you click on either one of them, you'll be directed to the corresponding profile.
<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中,
In my apprunner.py, I have
@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")
但是,我的问题是,当我单击任一按钮时,URL总是像"127.0.0.1:5000/profile"之类的东西.但是,我希望它看起来像" http://127.0.0.1:5000/profile1 "或" http://127.0.0.1:5000/profile2 ".
However, my problem is when I click on either button, the url will always be something like "127.0.0.1:5000/profile". But, I want it to look like "http://127.0.0.1:5000/profile1" or "http://127.0.0.1:5000/profile2".
我一直在寻找有关如何在线生成动态URL的解决方案,但是它们都不适合单击按钮.
I have looked for solution on how to generate dynamic URL online, but none of them works for button click.
提前谢谢!
推荐答案
@app.route('/profile<int:user>')
def profile(user):
print(user)
您可以在REPL上对其进行测试:
You can test it on a 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'
如何将 user
参数传递到新路由取决于您的需求.如果您需要 profile1
和 profile2
的硬编码路由,则可以分别传递 user = 1
和 user = 2
.如果要以编程方式生成这些链接,请取决于这些配置文件的存储方式.
how you pass the user
parameter to your new route depends on what you need. If you need hardcoded routes for profile1
and profile2
you can pass user=1
and user=2
respectively. If you want to generate those links programatically, depends on how these profiles are stored.
否则,您可以将请求对象中已解析的元素重定向
而不是 render_template
重定向到 url_for
.这意味着有两条路线
Otherwise you could redirect
instead of render_template
, to the url_for
with the parsed element in the request object. This means having two routes
@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))
如 http://exploreflask.com/en/latest/views.html#url-converters
@app.route('/user/<username>')
def profile(username):
pass
@app.route('/user/id/<int:user_id>')
def profile(user_id):
pass
我们还可以使用第二个视图来查找字符串.将会为/user/id/Q29kZUxlc3NvbiEh/调用,而第一个会为/user/id/124调用.
We could have a second view that looks for a string as well. That would be called for /user/id/Q29kZUxlc3NvbiEh/ while the first would be called for /user/id/124.
这篇关于在Flask中,如何在单击按钮时生成动态URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!