首页 > 解决方案 > 接收错误;AttributeError:在 return 语句中使用 render_template 时,“NoneType”对象没有属性“app”

问题描述

我正在尝试使用网络浏览器显示绘制的图形。但是 return 语句中的渲染模板抛出错误。以下是使用的代码和收到的错误。

蟒蛇代码:

from flask import Flask, render_template, Response
import io
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
import numpy as np

app = Flask(__name__,template_folder = 'D:/DATA_SETS')

@app.route('/html_example')
def myplot():
    with app.app_context():
        plt.figure()
        t = range(0,6,1)
        x= np.sin(t)
        plt.plot(t,x)
        plt.savefig('D:/DATA_SETS/new_plot.png')
        return Response(render_template('template_1.html', name = 'new_plot', url ='D:/DATA_SETS/new_plot.png'))

f = myplot()

if 1 == 1:
    app.run(debug=True)

模板 template_1.html

<!doctype html>
<html>
   <body>

      <h1>Performance</h1>

        <p>{{ name }}</p>

        <img src={{ url}} alt="Chart" height="42" width="42">

   </body>
</html>

预期:函数返回的图像应以编写的 HTML 格式显示。

当前:网页显示“未找到错误”。查看的网页是' http://localhost:5000/html_example '

标签: pythonhtmlflaskrendering

解决方案


您需要使用 app.app_context 函数将您的代码包装起来。您的代码将与此类似:

app = Flask(__name__,template_folder = 'templates')

@app.route('/')
def myplot():
    with app.app_context():
       plt.figure()
       t = range(0,6,1)
       x= np.sin(t)
       plt.plot(t,x)
       plt.savefig('D:/DATA_SETS/new_plot.png')
       return Response(render_template('template_1.html', name = 'new_plot', 
       url ='D:/DATA_SETS/new_plot.png'))

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

推荐阅读