如何在Django BinaryField中存储matplotlib图,然后将其直接呈现给模板?
答案 0 :(得分:2)
这些是我用来将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 }}" />