如何在媒体文件夹中保存生成的图表

时间:2015-03-04 01:07:13

标签: python django

我试图存储在django中生成的简单正弦图,并将其作为静态媒体保存在媒体文件夹中。

这是我生成图表但未保存图片的views.py:

from django.shortcuts import render
from numpy import arange, sin, pi, radians
from matplotlib import pylab
from pylab import *
import PIL
import PIL.Image
import StringIO
from django.http import HttpResponse

def graph(request):
    if request.POST.get("choice") == "True":
        x = arange(0.0,1.0,0.01)
        y = sin(2*pi*x)
        plt.plot(x,y)

        buffer = StringIO.StringIO()
        canvas = pylab.get_current_fig_manager().canvas
        canvas.draw()
        graphIMG = PIL.Image.fromstring("RGB", canvas.get_width_height(), canvas.tostring_rgb())
        graphIMG.save(buffer,"PNG")
        pylab.close()

        return HttpResponse(buffer.getvalue(), content_type="image/png")

    else :
        error_message='Please select an option'
        return render(request, 'graph/graph.html', {'error_message': error_message})

代码是从sentdex的youtube教程的教程中修改的: https://www.youtube.com/watch?v=zxbCkftGyds&list=PLQVvvaa0QuDcTDEowl-b5nQlaDaD82r_s&index=15

1 个答案:

答案 0 :(得分:1)

将图片保存到MEDIA_ROOT并返回重定向到它:

import os
from django.conf import settings
from django.shortcuts import redirect

file_name = 'graph.png'
full_path = os.path.join(settings.MEDIA_ROOT, file_name)
with open(full_path, 'w') as f:
    f.write(buffer.getvalue())
return redirect(settings.MEDIA_URL + file_name)