gpt4 book ai didi

python - Django 在使用 matplotlib 示例时出错

转载 作者:太空狗 更新时间:2023-10-29 20:46:47 29 4
gpt4 key购买 nike

我正在测试 Django 和 matplotlib 的几个案例,例如 this questionin french .

每次,它都可以在我的 mac 上运行,但不能在我的服务器上运行,我收到以下错误:

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

这是一个最小的片段:

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

我试过更新matplotlib、django等,但是什么也没做...

最佳答案

目前matplotlib的写函数require the seek ducktype在文件中使用响应。您可以像这样写入缓冲区:

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

关于python - Django 在使用 matplotlib 示例时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49542459/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com