Last active
January 3, 2024 14:37
-
-
Save Genarito/208164e1da82f0fd08e62cbac31e79f6 to your computer and use it in GitHub Desktop.
Django template tag for encoding images in base64 and rendering with server with Python 3.x
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import template | |
from django.contrib.staticfiles.finders import find as find_static_file | |
import base64 | |
register = template.Library() | |
def get_file_data(file_path: str) -> bytes: | |
""" | |
@param file_path: Path of the file to get the data | |
""" | |
with open(file_path, 'rb') as f: | |
data = f.read() | |
f.close() | |
return data | |
@register.simple_tag | |
def encode_static_base_64(path: str) -> str: | |
""" | |
A template tag that returns an encoded string representation of a static file | |
Usage:: | |
{% encode_static_base_64 path [encoding] %} | |
Examples:: | |
<img src="{% encode_static_base_64 'path/to/img.png' %}"> | |
""" | |
try: | |
file_path = find_static_file(path) | |
if file_path is None: | |
return '' | |
ext = file_path.split('.')[-1] | |
file_str = base64.b64encode(get_file_data(file_path)).decode('utf-8') | |
return f"data:image/{ext};base64,{file_str}" | |
except IOError: | |
return '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If the file doesn't exist, this will crash and prevent the template from rendering. I fixed that by catching it here: