我正在阅读烧瓶快速启动指南,但是带变量的路由的例子并不适用于我。
from flask import Flask
app = Flask(__name__)
@app.route('/') # fine
def index():
return 'Index Page'
@app.route('/hello') # fine
def hello():
return 'Hello World!'
@app.route('/user/<username>') # <- fails unless trailing slash here
def show_user_profile(username):
return 'User {}'.format(username)
if __name__ == '__main__':
app.run()@app.route('/user/<username>/'),则http://127.0.0.1:5000/user/bob重定向到http://127.0.0.1:5000/user/bob/,页面将正确呈现。我也试过这个代码和指南中的代码完全一样。我的第一个要点中的错误是预期的吗?快速启动版本中的代码应该工作吗?还是我误解了什么?
我使用Python2.7.10,烧瓶0.10.1,Werkzeug 0.10.4
发布于 2015-06-26 12:00:15
我在python2中尝试了这个例子,它工作得很好,但是在您所描述的python3问题中会发生。你用的是第三版吗?如果你这么做了你确定你真的需要它吗?
看看这个http://flask.pocoo.org/docs/0.10/python3/#python3-support
发布于 2015-06-26 15:50:57
这段代码已经在我的机器上运行,上面有Python2.7。
如果您使用的是多个参数,则代码中遗漏了{0}。
from flask import Flask
app = Flask(__name__)
@app.route('/') # fine
def index():
return 'Index Page'
@app.route('/hello') # fine
def hello():
return 'Hello World!'
@app.route('/user/<username>') # <- fails unless trailing slash here
def show_user_profile(username):
if request.url[-1] != '/':
return redirect(request.url + '/')
return 'User {0}'.format(username)
if __name__ == '__main__':
app.run(),正如您所观察到的,我又添加了两行代码
if request.url[-1] != '/':
return redirect(request.url + '/')以上线路将确保带有尾随斜线的线路仍能正常工作。您将需要操作任何其他path,而不是/,以防止需要它。请试试这个密码。
https://stackoverflow.com/questions/31072475
复制相似问题