def __getitem__(self, alias):
try:
return self._engines[alias]
except KeyError:
try:
params = self.templates[alias]
except KeyError:
raise InvalidTemplateEngineError(
"Could not find config for '{}' "
"in settings.TEMPLATES".format(alias))
# If importing or initializing the backend raises an exception,
# self._engines[alias] isn't set and this code may get executed
# again, so we must preserve the original params. See #24265.
params = params.copy()
backend = params.pop('BACKEND')
engine_cls = import_string(backend)
engine = engine_cls(params)
self._engines[alias] = engine
return engine
python类TEMPLATES的实例源码
def check_setting_app_dirs_loaders(app_configs, **kwargs):
passed_check = True
for conf in settings.TEMPLATES:
if not conf.get('APP_DIRS'):
continue
if 'loaders' in conf.get('OPTIONS', {}):
passed_check = False
return [] if passed_check else [E001]
def __init__(self, templates=None):
"""
templates is an optional list of template engine definitions
(structured like settings.TEMPLATES).
"""
self._templates = templates
self._engines = {}
def check_setting_app_dirs_loaders(app_configs, **kwargs):
passed_check = True
for conf in settings.TEMPLATES:
if not conf.get('APP_DIRS'):
continue
if 'loaders' in conf.get('OPTIONS', {}):
passed_check = False
return [] if passed_check else [E001]
def check_string_if_invalid_is_string(app_configs, **kwargs):
errors = []
for conf in settings.TEMPLATES:
string_if_invalid = conf.get('OPTIONS', {}).get('string_if_invalid', '')
if not isinstance(string_if_invalid, six.string_types):
error = copy.copy(E002)
error.msg = error.msg.format(string_if_invalid, type(string_if_invalid).__name__)
errors.append(error)
return errors
def enable(self):
return override_settings(TEMPLATES=[{
**settings.TEMPLATES[0],
'BACKEND': self.ENGINE_BACKENDS[self]
}])
def check_setting_app_dirs_loaders(app_configs, **kwargs):
passed_check = True
for conf in settings.TEMPLATES:
if not conf.get('APP_DIRS'):
continue
if 'loaders' in conf.get('OPTIONS', {}):
passed_check = False
return [] if passed_check else [E001]
def check_string_if_invalid_is_string(app_configs, **kwargs):
errors = []
for conf in settings.TEMPLATES:
string_if_invalid = conf.get('OPTIONS', {}).get('string_if_invalid', '')
if not isinstance(string_if_invalid, six.string_types):
error = copy.copy(E002)
error.msg = error.msg.format(string_if_invalid, type(string_if_invalid).__name__)
errors.append(error)
return errors
def check_setting_app_dirs_loaders(app_configs, **kwargs):
passed_check = True
for conf in settings.TEMPLATES:
if not conf.get('APP_DIRS'):
continue
if 'loaders' in conf.get('OPTIONS', {}):
passed_check = False
return [] if passed_check else [E001]
def check_string_if_invalid_is_string(app_configs, **kwargs):
errors = []
for conf in settings.TEMPLATES:
string_if_invalid = conf.get('OPTIONS', {}).get('string_if_invalid', '')
if not isinstance(string_if_invalid, six.string_types):
error = copy.copy(E002)
error.msg = error.msg.format(string_if_invalid, type(string_if_invalid).__name__)
errors.append(error)
return errors
def test_stacktraces_have_templates(client, django_elasticapm_client):
# only Django 1.9+ have the necessary information stored on Node/Template
# instances when TEMPLATE_DEBUG = False
TEMPLATE_DEBUG = django.VERSION < (1, 9)
with mock.patch("elasticapm.traces.TransactionsStore.should_collect") as should_collect:
should_collect.return_value = False
TEMPLATES_copy = deepcopy(settings.TEMPLATES)
TEMPLATES_copy[0]['OPTIONS']['debug'] = TEMPLATE_DEBUG
with override_settings(
TEMPLATE_DEBUG=TEMPLATE_DEBUG,
TEMPLATES=TEMPLATES_copy,
**middleware_setting(django.VERSION, [
'elasticapm.contrib.django.middleware.TracingMiddleware'
])
):
resp = client.get(reverse("render-heavy-template"))
assert resp.status_code == 200
transactions = django_elasticapm_client.instrumentation_store.get_all()
assert len(transactions) == 1
transaction = transactions[0]
assert transaction['result'] == 'HTTP 2xx'
spans = transaction['spans']
assert len(spans) == 2, [t['name'] for t in spans]
expected_names = {'list_users.html', 'something_expensive'}
assert {t['name'] for t in spans} == expected_names
assert spans[0]['name'] == 'something_expensive'
# Find the template
for frame in spans[0]['stacktrace']:
if frame['lineno'] == 4 and frame['filename'].endswith(
'django/testapp/templates/list_users.html'
):
break
else:
assert False is True, "Template was not found"
def _template_names(proj_only=False):
for engine in settings.TEMPLATES:
if (engine['BACKEND']
== 'django.template.backends.django.DjangoTemplates'):
for template_dir in chain(engine['DIRS'],
get_app_template_dirs('templates')):
if not proj_only or template_dir.startswith(settings.BASE_DIR):
for dirpath, dirnames, filenames in os.walk(template_dir):
for template_name in filenames:
yield os.path.join(dirpath[len(template_dir)+1:],
template_name)
else:
raise NotImplementedError(
"Currently only supports default DjangoTemplates backend."
)
def check_setting_app_dirs_loaders(app_configs, **kwargs):
passed_check = True
for conf in settings.TEMPLATES:
if not conf.get('APP_DIRS'):
continue
if 'loaders' in conf.get('OPTIONS', {}):
passed_check = False
return [] if passed_check else [E001]
def check_string_if_invalid_is_string(app_configs, **kwargs):
errors = []
for conf in settings.TEMPLATES:
string_if_invalid = conf.get('OPTIONS', {}).get('string_if_invalid', '')
if not isinstance(string_if_invalid, six.string_types):
error = copy.copy(E002)
error.msg = error.msg.format(string_if_invalid, type(string_if_invalid).__name__)
errors.append(error)
return errors
def check_setting_app_dirs_loaders(app_configs, **kwargs):
passed_check = True
for conf in settings.TEMPLATES:
if not conf.get('APP_DIRS'):
continue
if 'loaders' in conf.get('OPTIONS', {}):
passed_check = False
return [] if passed_check else [E001]
def check_setting_app_dirs_loaders(app_configs, **kwargs):
passed_check = True
for conf in settings.TEMPLATES:
if not conf.get('APP_DIRS'):
continue
if 'loaders' in conf.get('OPTIONS', {}):
passed_check = False
return [] if passed_check else [E001]
def check_setting_app_dirs_loaders(app_configs, **kwargs):
passed_check = True
for conf in settings.TEMPLATES:
if not conf.get('APP_DIRS'):
continue
if 'loaders' in conf.get('OPTIONS', {}):
passed_check = False
return [] if passed_check else [E001]
def check_string_if_invalid_is_string(app_configs, **kwargs):
errors = []
for conf in settings.TEMPLATES:
string_if_invalid = conf.get('OPTIONS', {}).get('string_if_invalid', '')
if not isinstance(string_if_invalid, six.string_types):
error = copy.copy(E002)
error.msg = error.msg.format(string_if_invalid, type(string_if_invalid).__name__)
errors.append(error)
return errors
def check_setting_app_dirs_loaders(app_configs, **kwargs):
passed_check = True
for conf in settings.TEMPLATES:
if not conf.get('APP_DIRS'):
continue
if 'loaders' in conf.get('OPTIONS', {}):
passed_check = False
return [] if passed_check else [E001]
def check_string_if_invalid_is_string(app_configs, **kwargs):
errors = []
for conf in settings.TEMPLATES:
string_if_invalid = conf.get('OPTIONS', {}).get('string_if_invalid', '')
if not isinstance(string_if_invalid, six.string_types):
error = copy.copy(E002)
error.msg = error.msg.format(string_if_invalid, type(string_if_invalid).__name__)
errors.append(error)
return errors