简体   繁体   中英

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

您可以更改响应的内容类型:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM