Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

python - Error in Django when using matplotlib examples

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 following error:

Internal Server Error: /mj/charts/mplimage.png
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py", line 35, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 128, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py", line 126, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/root/src/jm/majority_judgment/views.py", line 39, in mplimage
    canvas.print_png(response)
  File "/usr/local/lib/python3.6/dist-packages/matplotlib/backends/backend_agg.py", line 526, in print_png
    with cbook.open_file_cm(filename_or_obj, "wb") as fh:
  File "/usr/lib/python3.6/contextlib.py", line 81, in __enter__
    return next(self.gen)
  File "/usr/local/lib/python3.6/dist-packages/matplotlib/cbook/__init__.py", line 624, in open_file_cm
    fh, opened = to_filehandle(path_or_file, mode, True, encoding)
  File "/usr/local/lib/python3.6/dist-packages/matplotlib/cbook/__init__.py", line 615, in to_filehandle
    raise ValueError('fname must be a PathLike or file handle')
ValueError: fname must be a PathLike or file handle
[28/Mar/2018 19:09:11] "GET /mj/charts/mplimage.png HTTP/1.1" 500 82804

Here is a minimal snippet:

def mplimage(request):
    f = matplotlib.figure.Figure()
    canvas = FigureCanvasAgg(f)
    response = HttpResponse(content_type='image/png')
    canvas.print_png(response)
    plt.close(f)
    return response

I have tried to update matplotlib, django and so on, but it did nothing...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...