Django, Redis and Image caching to improve scalability

So I'm working with EC2 and S3bucket and Redis cluster.

The idea is that the image gets stored in the cache and gets retrieve from the cache before going to my S3bucket which is very demanding.

I can cache and retrieve already, as I've tried just caching the S3 image url.

All good till here, but that does not make the response any faster or at least not visibly faster.

So the solution here is to store the image itself and this is how I'm doing it.

def get_description(self, obj):
    image_key = f"category_img_ccc{obj.pk}"
    image_b64 = cache.get(image_key)
    if not image_b64:
        illustration_image = obj.description
        if illustration_image:
            image_url = illustration_image.url
            response = requests.get(image_url, stream=True)
            image = response.content
            image_b64 = base64.b64encode(image)
            cache.set(image_key, image_b64, None)
    if image_b64:
        return image_b64.decode("utf-8")
    else:
        return None

And the frontend should then encode it and render this correct ?

The response though looks very ugly as you can imagine the decoded image is a quite long char string.

Is this the way to go?

Can anyone shine some lights in this regard please.

Back to Top