Flask app.route(“/index”)或(“/index.html”)的烧瓶路由的最佳实践

Flask app.route(“/index”)或(“/index.html”)的烧瓶路由的最佳实践,flask,Flask,是否有在Flask中定义应用程序路由以添加后缀.html的约定?e、 g, @app.route("/index", methods=['GET']) def index_func(){ return render_template("index.html") } @app.route("/index.html", methods=['GET']) def index_func(){ return render_tem

是否有在Flask中定义应用程序路由以添加后缀.html的约定?e、 g,

@app.route("/index", methods=['GET'])
def index_func(){
    return render_template("index.html")
}

@app.route("/index.html", methods=['GET'])
def index_func(){
    return render_template("index.html")
}

哪种做法最好?谢谢。

No.1您在python中定义函数的方式是错误的

def func(){

}
行不通。相反,您可以定义如下函数:

def func():
    print("Hi")
然后,来到您将使用的路线声明

@app.route("/index")
def index_func():
    return render_template("index.html")

另外请注意,当您只想接收GET方法时,不必指定方法=['GET']

在这种情况下,最佳做法是使用“/”作为索引,避免同时使用“/index”和“/index.html”。索引页是主页的另一个名称,它是站点根页面“/”的同义词。所有其他路由都必须加上前缀,因此“/index”、“/home”等是多余的


至于向路由添加文件扩展名,这不仅是不必要的,而且如果您希望使用该路由为不同的内容类型提供服务,将来可能会错过。例如,如果您希望为移动和SPA客户端提供同一页面的JSON版本,该怎么办?我不知道有任何资料表明省略文件扩展名是一种最佳实践,但它隐含在Flask文档中的每个路由示例都省略了文件扩展名。例如,提供HTML页面的示例没有在路由中包含.HTML后缀。

我认为您应该先学习Python,然后再学习flask。这不是Python中定义函数的方式。