本文介绍了将matplotlib图存储在Django模型BinaryField中,然后直接从数据库中渲染它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将matplotlib图存储在Django BinaryField中,然后将其直接呈现到模板中?

How can I store a matplotlib plot in a Django BinaryField then render it directly to a template?

推荐答案

这些是我用来将matplotlib图像保存为BinaryField类型的命令:

These are the commands I use to save a matplotlib image to a BinaryField type:

该字段(我还没说过将二进制存储在单独的表中是一种好习惯):

The field (I haven't seen anything saying storing binary in a separate table is good practice):

class Blob(models.Model):
    blob = models.BinaryField(blank=True, null=True, default=None)

要生成并保存图像,请执行以下操作:

To generate and save the image:

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中创建以下内容:

To display it, I create the following in 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 }}" />

这篇关于将matplotlib图存储在Django模型BinaryField中,然后直接从数据库中渲染它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 07:54