Error in Django when using matplotlib examples

前端 未结 2 1739
旧巷少年郎
旧巷少年郎 2020-12-11 02:58

I am testing several cases of Django and matplotlib such as this question or in french.

Each time, it works on my mac, but does not on my server, where I receive the

相关标签:
2条回答
  • 2020-12-11 03:28

    At the moment, matplotlib's writing functions require the seek ducktype to use the response at a file. You can write to a buffer, like this:

    import io
    
    def mplimage(request):
        f = matplotlib.figure.Figure()
    
        # Code that sets up figure goes here; in the question, that's ...
        FigureCanvasAgg(f)
    
        buf = io.BytesIO()
        plt.savefig(buf, format='png')
        plt.close(f)
        response = HttpResponse(buf.getvalue(), content_type='image/png')
        return response
    
    0 讨论(0)
  • 2020-12-11 03:42

    You can just replace the response with a buffer and then add the buffer to the response. This will give an appropriate object to canvas.print_png() and keep code changes to a minimum.

    def mplimage(request):
        f = matplotlib.figure.Figure()
        buf = io.BytesIO()
        canvas = FigureCanvasAgg(f)
        canvas.print_png(buf)
        response=HttpResponse(buf.getvalue(),content_type='image/png')
        # if required clear the figure for reuse 
        f.clear()
        # I recommend to add Content-Length for Django
        response['Content-Length'] = str(len(response.content))
        #
        return response
    
    0 讨论(0)
提交回复
热议问题