【问题标题】:django pillow loading multiple images is slowdjango枕头加载多个图像很慢
【发布时间】:2021-09-01 10:33:53
【问题描述】:

我正在从 api 获取图像并在 django 应用程序中呈现。以这种方式加载图像真的很慢。

模板标签

def url(id):
    url = f'http://api.com/image?id={id}'
    response = requests.get(url)
    img = Image.open(BytesIO(response.content))
    data = BytesIO()
    img.save(data, "PNG")
    data.seek(0)
    encoded_img_data = base64.b64encode(data.getvalue())
    return encoded_img_data.decode('utf-8')

html

<img src="data:image/png;base64,{{row.image_md5|url}}" />

它可以工作,但加载图像需要 1 秒。有没有办法以这种方式更快地加载所有图像?

【问题讨论】:

    标签: python django image performance python-imaging-library


    【解决方案1】:

    你检查过瓶颈是什么吗? 可能是 API 太慢了。

    你可以用这个来计时,例如:

    import time
    start_time = time.time()
    url = f'http://api.com/image?id={id}'
    response = requests.get(url)
    end_time = time.time() - start_time
    print(end_time)
    

    【讨论】:

    • 提取 6 张图像需要 16 秒,2 张图像需要 4.5 秒,其余的需要 1.2 -1.5
    • 那么你的 API 不是问题吗?如果我们用 1.2 秒拍摄 4 张图像,用 4.5 秒拍摄 2 张​​图像,则为:4.8 + 9 = 13.8 秒。这已经是整个加载时间的 85%。您可以做的是使用 ajax 加载图像并首先显示占位符,然后在需要显示多次时缓存结果。另一种解决方案可能是使用 cron/自动任务来提取您需要的所有图像,然后将其缓存。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    相关资源
    最近更新 更多