簡體   English   中英

Python Flask-圖像代理

[英]Python Flask - image proxy

我正在尋找一種從網絡獲取圖像並將其返回給客戶端的方法(無需先保存到磁盤)。 像這樣(從此處獲取 ):

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'])

上面的代碼正在工作,但速度確實很慢。
還有更好的方法嗎?

為什么不使用Redis緩存和代理圖像? 我編寫了一個Web應用程序,需要從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')

請注意,上面的示例將僅在有人訪問時獲取並緩存該圖像,因此可能會在第一時間花費一些時間。 您可以先自己獲取圖像。 就我而言(我使用上面的方法),我很好。

最初的想法來自小狗的眼睛 閱讀源代碼以獲取更多詳細信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM