How to create graphics on the fly using cherry

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

+3
source share
2 answers

You need to set the header of the content of the response type manually, either in the application configuration using the tool response.headersor in the handler method.

There are two parameters to the handler method on the MimeDecorator page of the Cherrypy Tools wiki page.

In the body of the method:

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

Wikis also define 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()
+6
source

You can change the type of response content:

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

Source: https://habr.com/ru/post/1723285/


All Articles