How to generate a graphic on the fly with cherrypy

cherrypy, dynamic, graph, python

Solution

You need to set the content-type header of the response manually, either in the app config, using the `response.headers` tool, or in the handler method.

In the handler method, there are two options covered on the MimeDecorator page of the Cherrypy Tools wiki.

In the method body:

def hello(self):
    cherrypy.response.headers['Content-Type']= 'image/png'
    return generate_image_data()

Or using the tool decorator in Cherrypy 3:

@cherrypy.tools.response_headers([('Content-Type', 'image/png')])
def hello(self):
    return generate_image_data()

The wiki also defines a custom decorator:

def mimetype(type):
    def decorate(func):
        def wrapper(*args, **kwargs):
            cherrypy.response.headers['Content-Type'] = type
            return func(*args, **kwargs)
        return wrapper
    return decorate

class MyClass:        
    @mimetype("image/png")
    def hello(self):
        return generate_image_data()

Problem

I am developing a small web application using cherrypy and I would like to generate some graphs from the data stored in a database. The web pages with tables are easy and I plan to use matplotlib for the graphs themselves, but how do I set the content-type for the method so they return images instead of plain text? Will cherrypy "sniff" the result and change the content-type automatically?

Original source