Simplified caching of get_default_timezone().

This commit is contained in:
Aymeric Augustin 2014-11-18 21:50:03 +01:00
parent dca33ac15d
commit e23240474b
2 changed files with 10 additions and 13 deletions

View File

@ -59,7 +59,7 @@ def update_connections_time_zone(**kwargs):
time.tzset() time.tzset()
# Reset local time zone cache # Reset local time zone cache
timezone._localtime = None timezone.get_default_timezone.cache_clear()
# Reset the database connections' time zone # Reset the database connections' time zone
if kwargs['setting'] == 'USE_TZ' and settings.TIME_ZONE != 'UTC': if kwargs['setting'] == 'USE_TZ' and settings.TIME_ZONE != 'UTC':

View File

@ -15,6 +15,7 @@ except ImportError:
pytz = None pytz = None
from django.conf import settings from django.conf import settings
from django.utils import lru_cache
from django.utils import six from django.utils import six
from django.utils.decorators import ContextDecorator from django.utils.decorators import ContextDecorator
@ -162,25 +163,21 @@ def get_fixed_timezone(offset):
name = sign + hhmm name = sign + hhmm
return FixedOffset(offset, name) return FixedOffset(offset, name)
# In order to avoid accessing the settings at compile time,
# wrap the expression in a function and cache the result.
_localtime = None
# In order to avoid accessing settings at compile time,
# wrap the logic in a function and cache the result.
@lru_cache.lru_cache()
def get_default_timezone(): def get_default_timezone():
""" """
Returns the default time zone as a tzinfo instance. Returns the default time zone as a tzinfo instance.
This is the time zone defined by settings.TIME_ZONE. This is the time zone defined by settings.TIME_ZONE.
""" """
global _localtime if isinstance(settings.TIME_ZONE, six.string_types) and pytz is not None:
if _localtime is None: return pytz.timezone(settings.TIME_ZONE)
if isinstance(settings.TIME_ZONE, six.string_types) and pytz is not None: else:
_localtime = pytz.timezone(settings.TIME_ZONE) # This relies on os.environ['TZ'] being set to settings.TIME_ZONE.
else: return LocalTimezone()
# This relies on os.environ['TZ'] being set to settings.TIME_ZONE.
_localtime = LocalTimezone()
return _localtime
# This function exists for consistency with get_current_timezone_name # This function exists for consistency with get_current_timezone_name