Django / Python - 将图像从 AWS S3 存储桶转换为 Base64?

Django / Python - Convert image from AWS S3 bucket to Base64?

我正在尝试使用图像 URL 将每个图像实例转换为 base64。所有图像都存储在我的 amazon-s3 存储桶中。不幸的是,我生成的加密没有在我的 recipe_plain.html 模板中显示图像。感谢任何帮助。

views.py

...
import base64

class RecipePlainView(DetailView):
    model = Recipe
    template_name = 'recipes/recipe_plain.html'

    def get_context_data(self, **kwargs):
        context = super(RecipePlainView, self).get_context_data(**kwargs)
        image = self.object.image
        image.open(mode='rb')
        context['recipe_image_base64'] = base64.b64encode(image.read())
        image.close()
        return context

recipe_plain.html

<img src="data:image;base64,{{ recipe_image_base64 }}" alt="{{ recipe.image.name }}">

问题是 context['recipe_image_base64'] 变量返回了以字节为单位的 base64 对象。这已使用 decode() 函数解决。

我还使用请求库简化了脚本并包含了验证。

import base64, requests

class RecipePlainView(DetailView):
    model = Recipe
    template_name = 'recipes/recipe_plain.html'

    def get_context_data(self, **kwargs):
        url = self.object.image.url
        r = requests.get(url)
        if r.status_code == 200:
            byteBase64 = base64.b64encode(requests.get(url).content)
            context['recipe_image_base64'] = byteBase64.decode("utf-8")
        else:
            context['recipe_image_base64'] = False

        return context