Django serve file in memory instead of saving on disk

Viewed 378

I want to render plot (matplotlib) in one place of code and then in ViewSet serve to it user without saving on disk. I tried to use io library to keep file in memory, but it seems that always something is wrong.

My code where I save plot on disk:

def some_func(self):
    ...generating plot...
    
    filename = self.generate_path()  # generate random name for file
    plt.savefig(filename, transparent=True)
    return filename

Code of ViewSet:

class SomeViewsSet(ViewSet):

    def create(self, request):
            ... some code ...

            path = some_func()
            name = path.split('/')[-1]
            with open(path, 'rb') as file:
                response = HttpResponse(file, content_type=guess_type(path)[0])
                response['Content-Length'] = len(response.content)
                response['Content-Disposition'] = f'attachment; filename={name}'
                return response
1 Answers

Make sure that you pass matplotlib a BytesIO object, and not a StringIO. Then get the bytes using getvalue(), and pass them to HttpResponse. If that's what you've already tried, please post your code and the error message you're seeing.

Related