【问题标题】:Custom routing in Flask appFlask 应用中的自定义路由
【发布时间】:2013-10-13 07:50:06
【问题描述】:

我一直在尝试了解如何生成动态 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'])

【问题讨论】:

  • 你说你“得到一个构建错误”。请更新您的问题并发布整个堆栈跟踪,以及导致构建错误发生的运行代码。
  • 发布您的模板。当我尝试使用 url_for 构建 url 时出现构建错误,flask 尝试为我尚未在应用程序上注册的端点构建 url。
  • 至于创建动态 url,你已经知道了。不过,设置path = 'foo' 是多余的。看起来您希望 'foo' 被传递到您的视图并在您的模板上设置,但如果您导航到 localhost:5000/,flask 将发送到 '/',完全错过了这条路线。很确定在您的方法签名中设置path 的默认值None 也是不必要的,因为您的index 视图函数的arg 将从请求URI 构建。永远不会使用默认值。

标签: python flask


【解决方案1】:

你可以使用add_url_rule():

def index(path=None):
    return render_template('index.html', path=path)

path = '/foo'
app.add_url_rule(path, 'index', index)

如果你经常这样做,你可能还想看看blueprint objects

【讨论】:

    【解决方案2】:

    你已经知道了它的长短。您需要做的就是使用/&lt;var&gt; 语法(或在适当的情况下使用/&lt;converter:var&gt; 语法)来装饰您的视图函数。

    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 字符串。如果您使用&lt;int:var&gt;&lt;float:var&gt; 转换器创建变量,它将在应用程序空间中为您转换为适当的类型。

    &lt;path:blah&gt; 转换器将匹配包含斜杠 (/) 的字符串,因此您可以传递 /blah/dee/blah 并且视图函数中的路径变量将包含该字符串。在不使用path 转换器的情况下,flask 会尝试将您的请求发送到在路由/blah/dee/blah 上注册的视图函数,因为普通的&lt;var&gt; 由uri 中的下一个/ 描述。

    所以看看我的小应用程序,/files/&lt;path:path&gt; 路由将提供它可以找到与用户在请求中发送的路径匹配的任何文件。我从文档here 中提取了这个示例。

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

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

    【讨论】:

      猜你喜欢
      • 2018-06-05
      • 1970-01-01
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多