Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用Django Rest框架为渲染的JPEG图像提供服务?_Python_Django_Image_Matplotlib_Django Rest Framework - Fatal编程技术网

Python 如何使用Django Rest框架为渲染的JPEG图像提供服务?

Python 如何使用Django Rest框架为渲染的JPEG图像提供服务?,python,django,image,matplotlib,django-rest-framework,Python,Django,Image,Matplotlib,Django Rest Framework,在调用我的Django API时,我尝试使用matplotlib生成一个映像,然后使用Django Rest框架将该映像返回给客户机 我知道,但他们不能让我达到目的 我想我应该创建一种自定义渲染器,然后将结果传递给视图。我不清楚这样的view.py应该是什么样子。真正理想的做法是能够在内存中生成图像,然后在不必将其保存为服务器上的物理文件的情况下为其提供服务 因此,我的应用程序目录中有图像渲染器render.py: # app/render.py from rest_framework impo

在调用我的Django API时,我尝试使用matplotlib生成一个映像,然后使用Django Rest框架将该映像返回给客户机

我知道,但他们不能让我达到目的

我想我应该创建一种自定义渲染器,然后将结果传递给视图。我不清楚这样的view.py应该是什么样子。真正理想的做法是能够在内存中生成图像,然后在不必将其保存为服务器上的物理文件的情况下为其提供服务

因此,我的应用程序目录中有图像渲染器render.py:

# app/render.py
from rest_framework import renderers
from matplotlib import pyplot as plt

class JPEGRenderer(renderers.BaseRenderer):
    media_type = 'image/jpeg'
    format = 'jpg'
    charset = None
    render_style = 'binary'

    def render(self, data, media_type=None, renderer_context=None):
        # data coming in would be a numpy array

        # Matplotlib can create the image from the numpy data array. 
        # It would be cool to generate and return this as a Bytes IO object 
        # to avoid persisting the file on my server as pass this to the view,
        # but how do I render it? 
        image = plt.imsave("contour_image.jpg", data, cmap='jet')
        return image
有没有可能有人能帮忙看风景

# app/views.py
from rest_framework import renderers
from app.render import JPEGRenderer

class ImageServer(renderers.BaseRenderer):

    renderer_classes = (JPEGRenderer, ) # Is this how to call it?
    
    # What format should the image be in here, before serving it? 
    # Do I need to serialize it somehow? 
    # Is it possible to do so with a Bytes IO object held in memory?

    return # How do I serve the image? `

如果我想渲染图像,我会使用
img
标记来渲染它