1

我正在尝试制作一个烧瓶网站,到目前为止它正在打印一个你好世界。当我尝试从输出文本转换为输出简单的 html 模板时,站点中断,并且出现以下错误。

这是我的代码:

from flask import render_template, Blueprint

recipes_blueprint = Blueprint('recipes', __name__, template_folder='templates')

@recipes_blueprint.route('/')
def index():
     return    
render_template('list.html')

我的 list.html 只是模板文件夹中的以下内容:

<h1>Test</h1>

完整的错误在这里:

2021-10-16 07:50:53,399:     from app import app as application  # noqa
2021-10-16 07:50:53,399: 
2021-10-16 07:50:53,399:   File "/home/jameshiven/mysite/app.py", line 3, in <module>
2021-10-16 07:50:53,399:     from products.views import products_bp
2021-10-16 07:50:53,399: 
2021-10-16 07:50:53,399:   File "/home/jameshiven/mysite/products/views.py", line 12, in <module>
2021-10-16 07:50:53,399:     render_template('list.html')
2021-10-16 07:50:53,399: 
2021-10-16 07:50:53,399:   File "/usr/local/lib/python3.9/site-packages/flask/templating.py", line 146, in render_template
2021-10-16 07:50:53,399:     ctx.app.update_template_context(context)
2021-10-16 07:50:53,400: 
4

2 回答 2

2

蓝图应该在烧瓶应用程序中注册以显示在应用程序中。

将您的代码修改为

from flask import render_template, Blueprint, Flask

recipes_blueprint = Blueprint('recipes', __name__, template_folder='templates')
app = Flask(__name__)
app.register_blueprint(recipes_blueprint)

@app.route('/')
def index():
    return render_template('list.html')

if __name__ == '__main__':
    app.run()

这里有一些例子,这里

于 2021-10-16T08:26:27.780 回答
1

您没有提供实际的异常消息,但我猜它是:

AttributeError: 'NoneType' object has no attribute 'app'

这是因为您的视图功能搞砸了。改成这样说:

@recipes_blueprint.route('/')
def index():
    return render_template('list.html')

app然后像 John 建议的那样使用对象注册您的蓝图。

于 2021-10-16T08:33:50.610 回答