根据Flask中端点的名称渲染模板?

问题描述 投票:0回答:2

我希望使代码更易于维护。现在“thing1”重复三次。有没有办法做到这一点

@app.route("/thing1")
def thing1():
     return render_template("thing1.ejs")

@app.route("/thing2")
def thing2():
     return render_template("thing2.ejs")

@app.route("/thing3")
def thing3():
     return render_template("thing3.ejs")

更像...

@app.route("/thing1")
def thing1():
     return render_template_name_of_function() # should render thing1


@app.route("/thing2")
def thing2():
     return render_template_name_of_function() # should render thing2

@app.route("/thing3")
def thing3():
     return render_template_name_of_function() # should render thing3
python flask
2个回答
1
投票

您可以尝试使用inspect模块读取函数信息,以获取当前函数名称:

import inspect

@app.route("/thing1")
def thing1():
     return render_template(inspect.stack()[0][3])

@app.route("/thing2")
def thing2():
     return render_template(inspect.stack()[0][3])

@app.route("/thing3")
def thing3():
     return render_template(inspect.stack()[0][3])

然后,您可以在inspect.stack()调用之后指定模板文件的扩展名,例如inspect.stack()[0][3] + '.html'


2
投票

这是如何做到的。

@app.route("/thing1")
def thing1():
     return render()

@app.route("/another_thing1")
def another_thing1():
     return render()

@app.route("/yet_anther_thing1")
def yet_antoher_thing1():
     return render()

def render():
    return render_template("thing1.ejs")

虽然,除非你认为绝对必要,否则我认为应该通过使用redirect("thing1")来完成。

© www.soinside.com 2019 - 2024. All rights reserved.