custom template loader Django

久未见 提交于 2021-02-07 09:51:03

问题


i am trying to write a custom template loader in django which serves index.html which is present in a s3 bucket. Following is my loader file

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

and in my settings i have set the template settings in following way.

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',
            ],
        },
    }
]

anf following is my view

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

# Create your views here.


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

but when i am trying to acces my end point i am getting

Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 217, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.6/site-packages/django/core/handlers/base.py", line 215, in _get_response response = response.render() File "/usr/local/lib/python3.6/site-packages/django/template/response.py", line 107, in render self.content = self.rendered_content File "/usr/local/lib/python3.6/site-packages/django/template/response.py", line 84, in rendered_content content = template.render(context, self._request) TypeError: render() takes 2 positional arguments but 3 were given

i am not able to find what i am doing wrong. any help is appreciated.


回答1:


You built a loader, but you are using it as backend/engine. Try this config:

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',
            ],
        },
    }
]

Note that setting OPTIONS['loaders'] will disable caching. See docs on cached.Loader.



来源:https://stackoverflow.com/questions/54143892/custom-template-loader-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!