且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用CherryPy返回HTTP响应中的图像

更新时间:2022-01-20 06:45:55

添加这些导入:

from cherrypy.lib import file_generator
import StringIO

然后像这样:

def index(self):
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
    cherrypy.response.headers['Content-Type'] = "image/png"

    buffer = StringIO.StringIO()
    surface.write_to_png(buffer)
    buffer.seek(0)

    return file_generator(buffer)

另外,如果您正在提供独立文件(即它不是网页的一部分)并且您不希望它被渲染到浏览器中,而是被视为要保存在磁盘上的文件,那么您还需要一个标题:

Additionaly, if you're serving standalone file (i.e. it's not a part of a web page) and you don't want it to be rendered into browser but rather treated as a file to save on a disk then you need one more header:

cherrypy.response.headers['Content-Disposition'] = 'attachment; filename="file.png"'




此外,它是否更好?在内存中创建并保存
这个图像(比如我正在尝试
)或者将它作为temp
文件写入磁盘并从那里提供服务?我只需
需要一次图像,然后它可以被
丢弃。

Also, is it better to create and hold this image in memory (like I'm trying to do) or write it to disk as a temp file and serve it from there? I only need the image once, then it can be discarded.

如果你想要的唯一的东西要做的是将此文件提供给浏览器,没有理由在服务器上的磁盘上创建它。恰恰相反 - 请记住,访问硬盘会带来性能损失。

If the only thing you want to do is to serve this file to a browser there is no reason to create it on a disk on the server. Quite the contrary - remember that accessing hard disk brings performance penalty.