Error in Django when using matplotlib examples

前端 未结 2 1749
旧巷少年郎
旧巷少年郎 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: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
    

提交回复
热议问题