@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。