到base64标签的静态图像失败

问题描述 投票:0回答:1

使用此标记代码将静态文件夹中的某些图像转换为模板中的base64:

Tags.py:

import datetime
import base64
from django import template
from django.conf import settings
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.contrib.staticfiles.finders import find as find_static_file

@register.simple_tag
def encode_static(path, encodign='base64', file_type='image'):
    """
    to use like this:
            <img src="{% encode_static 'path/to/img.png' %}" />
    """
    try:
        file_path = find_static_file(path)
        ext = file_path.split('.')[-1]
        file_str = get_file_data(file_path).decode('utf-8')
        return "data:{0}/{1};{2}, {3}".format(file_type, ext, encodign, file_str)
    except IOError:
        return ''

def get_file_data(file_path):
    """ Return base 64 archivo """
    with open(file_path, 'rb') as f:
        data = base64.b64encode(f.read())
        f.close()
        return data

这是我的项目文件夹结构:

MyProject
  MyProject
    Lib
      Static
        MyApp
          Images
            Header.png

还有我在base.py中的静态目录conf:

STATIC_URL = '/Static/'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "Lib/Static"),
]

但是当我像这样从模板调用标签时:

<img src="{% encode_static '/MyApp/Images/Header.png' %}" />

我一直收到此错误:

The joined path (/MyApp/Images/Header.png) is located outside of the
base path component (MyProject/MyProject/Lib/Static)

没有任何意义,它确实在那个位置内,知道为什么会这样吗?

python django tags base64 tobase64string
1个回答
1
投票
您应该使用不带/的相对路径
© www.soinside.com 2019 - 2024. All rights reserved.