自定义模板加载器Django

时间:2019-01-11 09:42:48

标签: django django-templates django-views

我正在尝试在Django中编写一个自定义模板加载器,该加载器提供s3存储桶中存在的index.html。以下是我的加载器文件

from django.conf import settings
from django.template import Origin, Engine
from django.template.loader import TemplateDoesNotExist
from django.template.loaders.base import Loader
from boto3.session import Session

ACCESS_KEY_NAME = getattr(settings, 'AWS_TEMPLATE_LOADING_ACCESS_KEY_ID', getattr(settings, 'AWS_TEMPLATE_LOADING_ACCESS_KEY_ID', None))
SECRET_KEY_NAME = getattr(settings, 'AWS_TEMPLATE_LOADING_SECRET_ACCESS_KEY', getattr(settings, 'AWS_TEMPLATE_LOADING_SECRET_ACCESS_KEY', None))
TEMPLATE_BUCKET = getattr(settings, 'AWS_TEMPLATE_BUCKET_NAME')


class Loader(Loader):
    is_usable = True

    def __init__(self, *args, **kwargs):
        params = args[0]
        options = params.pop('OPTIONS').copy()
        options.setdefault('autoescape', True)
        options.setdefault('debug', settings.DEBUG)
        options.setdefault('file_charset', settings.FILE_CHARSET)
        libraries = options.get('libraries', {})
        session = Session(aws_access_key_id=ACCESS_KEY_NAME,
                          aws_secret_access_key=SECRET_KEY_NAME)
        s3 = session.resource('s3')
        self.bucket = s3.Bucket(TEMPLATE_BUCKET)
        super(Loader, self).__init__(*args, **kwargs)
        self.engine = Engine(dirs=params['DIRS'], context_processors=options, loaders=Loader)

    def getKeys(self):
        keys_objects = []
        for obj in self.bucket.objects.all():
            key = obj.key
            keys_objects.append({
                'key': key,
                'object': obj
            })
        return keys_objects

    def get_contents(self, origin):
        try:
            keys_objects = self.getKeys()
            for key_object in keys_objects:
                if key_object['key'] == origin:
                    return key_object['object'].get()['Body'].read()
        except FileNotFoundError:
            raise TemplateDoesNotExist(origin)


    def get_template_sources(self, template_name, template_dirs=None):
        tried = []
        yield Origin(
            name=template_name,
            template_name=template_name,
            loader=self,
        )
        tried.append('/index.html')
        if tried:
            error_msg = "Tried Keys %s" % tried
        else:
            error_msg = "Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory."
        raise TemplateDoesNotExist(error_msg)

    get_template_sources.is_usable = True

,在我的设置中,我已经按照以下方式设置了模板设置。

TEMPLATES = [
    {
        'BACKEND': 'app.s3template_loader.Loader',
        'DIRS': [
            'index.html'
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    }
]

以下是我的观点

from django.shortcuts import render
from django.views.generic import TemplateView

# Create your views here.


class AngularAppView(TemplateView):
    template_name = 'index.html'

但是当我尝试进入终点时,我会得到

  

内部服务器错误:/追溯(最近一次呼叫最近):文件   “ /usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py”,   第41行,在内部       response = get_response(request)文件“ /usr/local/lib/python3.6/site-packages/django/core/handlers/base.py”,   _get_response中的第217行       响应= self.process_exception_by_middleware(e,request)文件“ /usr/local/lib/python3.6/site-packages/django/core/handlers/base.py”,   _get_response中的第215行       response = response.render()文件“ /usr/local/lib/python3.6/site-packages/django/template/response.py”,   第107行,在渲染中       self.content = self.rendered_content文件“ /usr/local/lib/python3.6/site-packages/django/template/response.py”,   第84行,在render_content中       content = template.render(context,self._request)TypeError:render()接受2个位置参数,但给出了3个

我找不到我做错的事情。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您构建了一个加载程序,但是您将其用作后端/引擎。试试这个配置:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            'index.html'
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'loaders': ['app.s3template_loader.Loader'],
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    }
]

请注意,设置OPTIONS['loaders']将禁用缓存。请参阅cached.Loader上的文档。