views:

241

answers:

2

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?

A: 

You can change the content type of the response:

cherrypy.response.headers['Content-Type'] = "image/png"
Ned Batchelder
+2  A: 

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()
ddaa