【问题标题】:Store matplotlib plots in a Django model BinaryField then render them directly from the database将 matplotlib 绘图存储在 Django 模型 BinaryField 中,然后直接从数据库中渲染它们
【发布时间】:2016-06-03 19:36:57
【问题描述】:

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

【问题讨论】:

    标签: django templates matplotlib model


    【解决方案1】:

    这些是我用来将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 数组;))
    • 糟糕,谢谢,已更正。除了与 Django-1.6 兼容之外,还有什么理由更喜欢 base64?似乎是自然的选择,而且效果很好。
    • 克里斯,因为它不需要解析第二个 url(在你的情况下是另一个数据库查询),你可以有一个 base64 array as an image source
    • 顺便说一句,我强烈建议你看看我的另一个问题,Matplotlib can't render multiple contour plots on Django,你当前的图表创建代码看起来会陷入同样的​​问题
    • 我没有看到这一点,因为我的脚本在单独的 Celery 进程中运行,但您在该问题上的选项 2 是一个很棒的发现,而且代码显然更好,所以我会更新。 (我坚持使用冗余 URL 调用以与 Dolphin 和 Android 库存浏览器兼容。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 2014-10-05
    相关资源
    最近更新 更多