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