简体   繁体   English

如何使用cherrypy生成动态图形

[英]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. 我正在使用cherrypy开发一个小型Web应用程序,我想从存储在数据库中的数据生成一些图表。 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? 带有表格的网页很简单,我打算使用matplotlib作为图形本身,但是如何设置方法的内容类型以便它们返回图像而不是纯文本? 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. 您需要在app config中使用response.headers工具或在handler方法中手动设置响应的content-type标头。

In the handler method, there are two options covered on the MimeDecorator page of the Cherrypy Tools wiki. 在处理程序方法中,Cherrypy Tools wiki的MimeDecorator页面上有两个选项。

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 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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