python - 在 Bottle 中使用流而不是 static_file 返回图像

标签 python stream bottle

我有一个使用 Bottle 框架用 Python 编写的简单服务器应用程序。在一条路线上,我创建了一个图像并将其写入流,我想将其作为响应返回。我知道如何使用 static_file 函数返回图像文件,但这对我来说成本很高,因为我需要先将图像写入文件。我想直接使用流对象提供图像。我该怎么做?

我当前的代码是这样的(文件版本):

@route('/image')
def video_image():
    pi_camera.capture("image.jpg", format='jpeg')

    return static_file("image.jpg",
                       root=".",
                       mimetype='image/jpg')

而不是这个,我想做这样的事情:

@route('/image')
def video_image():
    image_buffer = BytesIO()
    pi_camera.capture(image_buffer, format='jpeg') # This works without a problem

    # What to write here?

最佳答案

只返回字节。 (您还应该设置 Content-Type header 。)

@route('/image')
def video_image():
    image_buffer = BytesIO()
    pi_camera.capture(image_buffer, format='jpeg') # This works without a problem

    image_buffer.seek(0) # this may not be needed
    bytes = image_buffer.read()
    response.set_header('Content-type', 'image/jpeg')
    return bytes

关于python - 在 Bottle 中使用流而不是 static_file 返回图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28029702/

相关文章:

python - 在 Networkit 中检索原始节点名称

c# - 通过局域网发送声音或流式传输声音

python - 如何访问模板中的请求数据

python - 如何从管理面板的字段中提取信息?

Python 开关函数

python - 如何将列表项从字符串转换为 int?

c++ - 如何清除String流中的内容?

c# - 将字节数组保存到文件

javascript - 我们如何在不使用 Javascript 的情况下向 python Bottle 服务器发送 GET 请求?

javascript - Bottle .py : sending data via javascript