diff --git a/django/utils/timezone.py b/django/utils/timezone.py index b8e40b031c..b545201bd3 100644 --- a/django/utils/timezone.py +++ b/django/utils/timezone.py @@ -16,6 +16,7 @@ except ImportError: from django.conf import settings from django.utils import six +from django.utils.decorators import ContextDecorator __all__ = [ 'utc', 'get_fixed_timezone', @@ -248,7 +249,7 @@ def deactivate(): del _active.value -class override(object): +class override(ContextDecorator): """ Temporarily set the time zone for the current thread. diff --git a/docs/ref/utils.txt b/docs/ref/utils.txt index e4164d2d34..c38579cb7a 100644 --- a/docs/ref/utils.txt +++ b/docs/ref/utils.txt @@ -901,6 +901,10 @@ appropriate entities. ``None``, the :ref:`current time zone ` is unset on entry with :func:`deactivate()` instead. + .. versionchanged:: 1.8 + + ``override`` is now usable as a function decorator. + .. function:: localtime(value, timezone=None) Converts an aware :class:`~datetime.datetime` to a different time zone, diff --git a/tests/utils_tests/test_timezone.py b/tests/utils_tests/test_timezone.py index ae78d68103..9414a6097e 100644 --- a/tests/utils_tests/test_timezone.py +++ b/tests/utils_tests/test_timezone.py @@ -71,6 +71,36 @@ class TimezoneTests(unittest.TestCase): finally: timezone.deactivate() + def test_override_decorator(self): + default = timezone.get_default_timezone() + + @timezone.override(EAT) + def func_tz_eat(): + self.assertIs(EAT, timezone.get_current_timezone()) + + @timezone.override(None) + def func_tz_none(): + self.assertIs(default, timezone.get_current_timezone()) + + try: + timezone.activate(ICT) + + func_tz_eat() + self.assertIs(ICT, timezone.get_current_timezone()) + + func_tz_none() + self.assertIs(ICT, timezone.get_current_timezone()) + + timezone.deactivate() + + func_tz_eat() + self.assertIs(default, timezone.get_current_timezone()) + + func_tz_none() + self.assertIs(default, timezone.get_current_timezone()) + finally: + timezone.deactivate() + def test_copy(self): self.assertIsInstance(copy.copy(timezone.UTC()), timezone.UTC) self.assertIsInstance(copy.copy(timezone.LocalTimezone()), timezone.LocalTimezone)