开发者

How to generate a graphic on the fly with cherrypy

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?


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


You can change the content type of the response:

cherrypy.response.headers['Content-Type'] = "image/png"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜