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

Python Flask应用程序中的自定义路由,python,flask,Python,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) path='foo' @app.route('/',methods

我一直在试图理解如何生成动态URL。我已经阅读了文档和几个示例,但不明白为什么这段代码不起作用:

path = 'foo'
@app.route('/<path:path>', methods=['POST'])
def index(path=None):
    # do some stuff...
    return flask.render_template('index.html', path=path)
path='foo'
@app.route('/',methods=['POST'])
def索引(路径=无):
#做些事情。。。
返回flask.render_模板('index.html',path=path)
我希望我的index.html模板能够提供给
/foo
,但事实并非如此。我得到一个构建错误。我错过了什么

如果我使用一个固定的路径,比如
/bar
,那么一切都可以正常工作

@app.route('/bar',methods=['POST'])
您可以使用:


你可能还想看看你是否经常这样做。

你已经知道了它的长短。您只需使用
/
语法(或适当的
/
语法)来修饰视图函数

从烧瓶导入烧瓶,渲染\u模板
app=烧瓶(名称)
@应用程序路径(“/”)
def index():
返回渲染模板('index.html')
@app.route('/',默认值={'word':'bird'})
def word_up(word):
返回render_模板('whattheword.html',word=word)
@app.route(“/files/”)
def SERVER_文件(路径):
从_目录返回发送_(app.config['UPLOAD_DIR',path,as_attachment=True)
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
app.debug=True
应用程序运行(端口=9017)
当Flask从URL中提取一个变量用于动态路由(如您尝试使用的)时,默认情况下,它将是Python中的unicode字符串。如果使用
转换器创建变量,它将在应用程序空间中为您转换为适当的类型

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

因此,看看我的小应用程序,
/files/
路由将提供它能找到的任何与用户请求时发送的路径匹配的文件。我从文档中提取了这个示例

此外,还可以通过关键字
arg
route()
decorator为变量URL指定默认值


如果您愿意,您甚至可以访问Werkzeug根据您在应用程序空间中指定查看功能和路线的方式构建的基础
url\u地图。要了解更多信息,请查看URL注册

你说你“得到一个构建错误”。请更新您的问题并发布整个堆栈跟踪,以及导致生成错误的运行代码。发布您的模板。当我尝试使用
url\u为
构建url,flask尝试为我尚未在应用程序上注册的端点构建url时,我会遇到构建错误。至于创建动态url,您已经做到了。不过,设置
path='foo'
是一个超级功能。看起来您希望将
'foo'
传递到视图中并在模板上进行设置,但如果导航到
localhost:5000/
,flask将被分派到
'/'
,完全错过此路径。可以肯定的是,在方法签名中的
path
上设置
None
的默认值也是不必要的,因为
索引
视图函数的参数将从请求URI生成。默认值永远不会被使用。
def index(path=None):
    return render_template('index.html', path=path)

path = '/foo'
app.add_url_rule(path, 'index', index)
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)