python - Flask 应用程序中的自定义路由

标签 python flask

我一直在努力了解如何生成动态 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)

我希望将我的 index.html 模板提供给 /foo,但事实并非如此。我收到构建错误。我错过了什么?

如果我使用固定路径,如 /bar,一切正常。

@app.route('/bar', methods=['POST'])

最佳答案

您已经了解了它的长短。您需要做的就是使用 /<var> 装饰您的 View 函数语法(或适当的 /<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)

当 Flask 像您尝试使用的那样从动态路由的 URL 中提取变量时,默认情况下它将是 Python 中的 unicode 字符串。如果您使用 <int:var> 创建变量或 <float:var>转换器,它将在应用程序空间中为您转换为适当的类型。

<path:blah>转换器将匹配包含斜杠 ( / ) 的字符串,因此您可以传递 /blah/dee/blah并且 View 函数中的路径变量将包含该字符串。不使用 path converter,flask 会尝试将你的请求发送到在路由 /blah/dee/blah 上注册的 View 函数,因为普通的 <var>由下/划定在 uri 中。

看看我的小应用程序,/files/<path:path> route 将提供它可以找到的与用户根据请求发送的路径相匹配的任何文件。我从文档中提取了这个例子 here .

此外,您可以通过关键字 arg 为变量 URL 指定默认值。到 route()装饰器。

如果需要,您甚至可以访问底层 url_map Werkzeug 根据您在应用程序空间中指定 View 函数和路由的方式构建。如需更多内容,请查看 api docs关于 URL 注册。

关于python - Flask 应用程序中的自定义路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19212980/

相关文章:

Python 线程 'While' 不正常

python - 为 Flask 测试客户端设置默认的 content_type

flask - SQLAlchemy 一对多查询输出

python - 我无法让这个简单的表单更新程序工作

c++ - C++ 和 Python 中的预定义文本替换

python - 由于 unicode 解码错误,无法在 pandas 中打开 csv 文件

python - pyqtgraph - 导入错误 : No module named pyqtgraph

python - os.path.exists 无法识别 C :\Windows\system32\drivers 下的子目录

python - Flask 如何通过 appbuilder 将字段设置为只读

python - 带有 Flask Python 的亚马逊 SES