【问题标题】:Python Flask - image proxyPython Flask - 图像代理
【发布时间】:2015-07-26 05:58:15
【问题描述】:

我正在寻找一种从网络获取图像并将其返回给客户端的方法(无需先保存到磁盘)。类似的东西(取自here):

import requests
from flask import Response, stream_with_context

@files_blueprint.route('/', methods=['GET'])
def get_image():  
    req = requests.get('http://www.example.com/image1.png', stream = True)
    return Response(stream_with_context(req.iter_content()), content_type = req.headers['content-type'])

上面的代码可以运行,但是速度很慢。
有更好的方法吗?

【问题讨论】:

  • 哪一部分慢? requests.getreturn Response?
  • 您可以在iter_content(chunk_size) 中尝试使用不同的尺寸。默认大小是1,这会很慢。请改用10242048
  • 我将 chunk_size 更改为 2048 - 好多了!谢谢!要将其发布为答案以便我标记它吗?

标签: python flask python-requests


【解决方案1】:

为什么不使用 redis 来缓存和代理您的图像? 我编写了一个需要从 API 服务器请求图像但有时可能会得到 403 禁止的网络应用程序,所以我从 API 服务器获取图像并缓存它们。

  • 之前: 客户端 -> API 服务器:可能会得到 403

  • 现在使用图像代理:

    • 未缓存:

      • 客户端 -> 我的服务器:没有找到
      • 我的服务器 -> API 服务器:获取图像,缓存它,发送到客户端
    • 缓存:

      • 客户端->我的服务器:找到它并从redis获取图像并发送回

区别在于:

  • 之前:客户端 API 服务器
  • 现在:客户端 我的服务器 API 服务器

在客户端直接从 API 服务器获取图片之前,可能会出现问题。现在,所有图像都指向我的服务器,所以我可以做更多的事情。

您还可以控制过期时间。使用强大的 redis,你应该很容易。

我会给你一个基本的例子来帮助你理解它。

from StringIO import StringIO

from flask import send_file, Flask
import requests
import redis

app = Flask(__name__)
redis_server = redis.StrictRedis(host='localhost', port=6379)

@app.route('/img/<server>/<hash_string>')
def image(server, hash_string):
    """Handle image, use redis to cache image."""
    image_url = 'http://www.example.com/blabla.jpg'
    cached = redis_server.get(image_url)
    if cached:
        buffer_image = StringIO(cached)
        buffer_image.seek(0)
    else:
        r = requests.get(image_url)  # you can add UA, referrer, here is an example.
        buffer_image = StringIO(r.content)
        buffer_image.seek(0)
        redis_server.setex(image_url, (60*60*24*7),
                           buffer_image.getvalue())
    return send_file(buffer_image, mimetype='image/jpeg')

请注意,上面的示例仅在有人访问时才会获取图像并对其进行缓存,因此第一次可能会花费一些时间。您可以先自己获取图像。在我的情况下(我使用上面的方式),我很好。

最初的想法来自puppy-eyes。阅读源代码了解更多详情。

【讨论】:

  • 感谢您的回答!虽然这很好用,但对我的任务来说太复杂了。 (我没有太多图片,也不需要缓存)
猜你喜欢
  • 2020-09-11
  • 2018-04-22
  • 2015-05-28
  • 1970-01-01
  • 2018-01-16
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多