python - 接收错误;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 '
解决方案
您需要使用 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)
推荐阅读
- sql - 使用 IN 条件 mariadb 时自动排序
- java - Java/Kotlin 使用可见的命令提示符运行 Runtime.getRuntime().exec()
- linq - 在 Select 函数中调用 .ToList() 时为空引用
- ruby-on-rails - Chrome Rails 会话的 Cookie 更改随机时间
- html - 按钮和文本重叠
- machine-learning - 高斯 RBF 核的用途
- ruby-on-rails - cookie 和 Rails 会话对象之间有什么关系?
- qt - 在 0x000000005207AAD7 (Qt5Core.dll) 处引发异常
- c++ - std::reverse 的替代方案以保留向量中的所有元素?
- rust - 从 Rust 中的结构中借用