我一直在努力了解如何生成动态Flask URL.我已经阅读了文档和几个示例,但无法弄清楚为什么此代码不起作用:
path = 'foo'
@app.route('/<path:path>', methods=['POST'])
def index(path=None):
# do some stuff...
return flask.render_template('index.html', path=path)
Run Code Online (Sandbox Code Playgroud)
我希望能够提供我的index.html模板/foo,但事实并非如此.我遇到了构建错误.我错过了什么?
如果我使用固定路径,那么/bar一切都可以正常运行.
@app.route('/bar', methods=['POST'])
你已经掌握了它的长短.您需要做的就是使用/<var>语法(或/<converter:var>适当的语法)来装饰视图函数.
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/<word>', defaults={'word': 'bird'})
def word_up(word):
return render_template('whatstheword.html', word=word)
@app.route('/files/<path:path>')
def serve_file(path):
return send_from_directory(app.config['UPLOAD_DIR'], path, as_attachment=True)
if __name__ == '__main__':
app.debug = True
app.run(port=9017)
Run Code Online (Sandbox Code Playgroud)
当Flask从您尝试使用的动态路由的URL中提取变量时,默认情况下它将是Python中的unicode字符串.如果使用<int:var>或<float:var>转换器创建变量,它将在应用程序空间中转换为适当的类型.
该<path:blah>转换器将匹配包含斜杠(串/),这样你就可以通过/blah/dee/blah在您的视图功能的路径变量将包含字符串.如果不使用path转换器,flask将尝试将您的请求发送到路由上注册的视图函数/blah/dee/blah,因为uri中<var>的下一个描述了plain /.
因此,查看我的小应用程序,该/files/<path:path>路径将提供它可以找到的任何文件,该文件与用户在请求中发送的路径相匹配.我从这里的文档中提取了这个例子.
另外,挖掘您可以通过关键字arg为route()装饰器指定变量URL的默认值.
如果需要,您甚至可以url_map根据在应用程序空间中指定视图函数和路径的方式访问Werkzeug构建的基础.有关更多内容需要咀嚼,请查看有关URL注册的api文档.