Skip to content

Instantly share code, notes, and snippets.

@jnothman
Last active December 6, 2017 22:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnothman/396a5d9ffa9816dfd01fb3dfb95afc42 to your computer and use it in GitHub Desktop.
Save jnothman/396a5d9ffa9816dfd01fb3dfb95afc42 to your computer and use it in GitHub Desktop.
Generic Django plot view for matplotlib plot rendering and serving
from django.views import View
from django.http import HttpResponse
MIMETYPES = {
'ps': 'application/postscript',
'eps': 'application/postscript',
'pdf': 'application/pdf',
'svg': 'image/svg+xml',
'png': 'image/png',
'jpeg': 'image/jpeg',
'tif': 'image/tiff',
'emf': 'application/emf'
}
class PlotView(View):
def get(self, request):
image_format = request.GET.get('fmt', 'svg')
fig = self.get_figure(request)
out = HttpResponse(content_type=MIMETYPES[image_format])
fig.savefig(out, format=image_format)
fig.clear()
return out
def get_figure(self, request):
raise NotImplementedError()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment