【发布时间】:2016-06-03 19:36:57
【问题描述】:
如何将 matplotlib 图存储在 Django BinaryField 中,然后直接渲染到模板?
【问题讨论】:
标签: django templates matplotlib model
如何将 matplotlib 图存储在 Django BinaryField 中,然后直接渲染到模板?
【问题讨论】:
标签: django templates matplotlib model
这些是我用来将matplotlib 图像保存到BinaryField 类型的命令:
该字段(我没有看到任何说将二进制文件存储在单独的表中是好的做法):
class Blob(models.Model):
blob = models.BinaryField(blank=True, null=True, default=None)
生成并保存图像:
import io
import matplotlib.pyplot as plt
import numpy as np
from myapp.models import Blob
# Any old code to generate a plot - NOTE THIS MATPLOTLIB CODE IS NOT THREADSAFE, see http://stackoverflow.com/questions/31719138/matplotlib-cant-render-multiple-contour-plots-on-django
t = np.arange(0.0, gui_val_in, gui_val_in/200)
s = np.sin(2*np.pi*t)
plt.figure(figsize=(7, 6), dpi=300, facecolor='w')
plt.plot(t, s)
plt.xlabel('time (n)')
plt.ylabel('temp (c)')
plt.title('A sample matplotlib graph')
plt.grid(True)
# Save it into a BytesIO type then use BytesIO.getvalue()
f = io.BytesIO() # StringIO if Python <3
plt.savefig(f)
b = Blob(blob=f.getvalue())
b.save()
为了显示它,我在myapp/views.py 中创建了以下内容:
def image(request, blob_id):
b = Blob.objects.get(id=blob_id)
response = HttpResponse(b.blob)
response['Content-Type'] = "image/png"
response['Cache-Control'] = "max-age=0"
return response
添加到myapp/urls.py:
url(r'^image/(?P<blob_id>\d+)/$', views.image, name='image'),
在模板中:
<img src="{% url 'myapp:image' item.blob_id %}" alt="{{ item.name }}" />
【讨论】:
value.getvalue 应该是 f.getvalue() (虽然我更喜欢渲染/存储为 base64 数组;))