Fixed #25753 -- Made get_format() cache the formats from Django settings

This commit is contained in:
Jaap Roes 2016-12-01 21:41:22 +01:00 committed by Claude Paroz
parent 1206d7fa57
commit 3188b49ee2
1 changed files with 34 additions and 26 deletions

View File

@ -112,32 +112,40 @@ def get_format(format_type, lang=None, use_l10n=None):
be localized (or not), overriding the value of settings.USE_L10N. be localized (or not), overriding the value of settings.USE_L10N.
""" """
format_type = force_str(format_type) format_type = force_str(format_type)
if use_l10n or (use_l10n is None and settings.USE_L10N): use_l10n = use_l10n or (use_l10n is None and settings.USE_L10N)
if lang is None: if use_l10n and lang is None:
lang = get_language() lang = get_language()
cache_key = (format_type, lang) cache_key = (format_type, lang)
try: try:
cached = _format_cache[cache_key] return _format_cache[cache_key]
if cached is not None: except KeyError:
return cached pass
except KeyError:
for module in get_format_modules(lang): # The requested format_type has not been cached yet. Try to find it in any
try: # of the format_modules for the given lang if l10n is enabled. If it's not
val = getattr(module, format_type) # there or if l10n is disabled, fall back to the project settings.
for iso_input in ISO_INPUT_FORMATS.get(format_type, ()): val = None
if iso_input not in val: if use_l10n:
if isinstance(val, tuple): for module in get_format_modules(lang):
val = list(val) try:
val.append(iso_input) val = getattr(module, format_type)
_format_cache[cache_key] = val if val is not None:
return val break
except AttributeError: except AttributeError:
pass pass
_format_cache[cache_key] = None if val is None:
if format_type not in FORMAT_SETTINGS: if format_type not in FORMAT_SETTINGS:
return format_type return format_type
# Return the general setting by default val = getattr(settings, format_type)
return getattr(settings, format_type) elif format_type in ISO_INPUT_FORMATS.keys():
# If a list of input formats from one of the format_modules was
# retrieved, make sure the ISO_INPUT_FORMATS are in this list.
val = list(val)
for iso_input in ISO_INPUT_FORMATS.get(format_type, ()):
if iso_input not in val:
val.append(iso_input)
_format_cache[cache_key] = val
return val
get_format_lazy = lazy(get_format, six.text_type, list, tuple) get_format_lazy = lazy(get_format, six.text_type, list, tuple)