Python django.utils.timezone.activate() Examples

The following are 30 code examples of django.utils.timezone.activate(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.utils.timezone , or try the search function .
Example #1
Source File: tests.py    From jinja2-django-tags with MIT License 6 votes vote down vote up
def test_localize(self):
        env = Environment(extensions=[DjangoL10n])
        template = env.from_string("{{ foo }}")
        context1 = {'foo': 1.23}
        date = datetime.datetime(2000, 10, 1, 14, 10, 12, tzinfo=timezone.utc)
        context2 = {'foo': date}

        translation.activate('en')
        self.assertEqual('1.23', template.render(context1))

        translation.activate('de')
        self.assertEqual('1,23', template.render(context1))

        translation.activate('es')
        timezone.activate('America/Argentina/Buenos_Aires')
        self.assertEqual('1 de Octubre de 2000 a las 11:10', template.render(context2))

        timezone.activate('Europe/Berlin')
        self.assertEqual('1 de Octubre de 2000 a las 16:10', template.render(context2))

        translation.activate('de')
        self.assertEqual('1. Oktober 2000 16:10', template.render(context2))

        timezone.activate('America/Argentina/Buenos_Aires')
        self.assertEqual('1. Oktober 2000 11:10', template.render(context2)) 
Example #2
Source File: test_timezone.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_override(self):
        default = timezone.get_default_timezone()
        try:
            timezone.activate(ICT)

            with timezone.override(EAT):
                self.assertIs(EAT, timezone.get_current_timezone())
            self.assertIs(ICT, timezone.get_current_timezone())

            with timezone.override(None):
                self.assertIs(default, timezone.get_current_timezone())
            self.assertIs(ICT, timezone.get_current_timezone())

            timezone.deactivate()

            with timezone.override(EAT):
                self.assertIs(EAT, timezone.get_current_timezone())
            self.assertIs(default, timezone.get_current_timezone())

            with timezone.override(None):
                self.assertIs(default, timezone.get_current_timezone())
            self.assertIs(default, timezone.get_current_timezone())
        finally:
            timezone.deactivate() 
Example #3
Source File: test_timezone.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_override(self):
        default = timezone.get_default_timezone()
        try:
            timezone.activate(ICT)

            with timezone.override(EAT):
                self.assertIs(EAT, timezone.get_current_timezone())
            self.assertIs(ICT, timezone.get_current_timezone())

            with timezone.override(None):
                self.assertIs(default, timezone.get_current_timezone())
            self.assertIs(ICT, timezone.get_current_timezone())

            timezone.deactivate()

            with timezone.override(EAT):
                self.assertIs(EAT, timezone.get_current_timezone())
            self.assertIs(default, timezone.get_current_timezone())

            with timezone.override(None):
                self.assertIs(default, timezone.get_current_timezone())
            self.assertIs(default, timezone.get_current_timezone())
        finally:
            timezone.deactivate() 
Example #4
Source File: timezoneMiddleware.py    From django-aws-template with MIT License 6 votes vote down vote up
def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)

        # Code to be executed for each request/response after
        # the view is called.

        tzname = request.session.get('django_timezone')

        if not tzname:
            # Get it from the Account. Should hopefully happens once per session
            user = request.user
            if user and not user.is_anonymous:
                tzname = user.time_zone
                if tzname:
                    request.session['django_timezone'] = tzname

        if tzname:
            timezone.activate(pytz.timezone(tzname))
        else:
            timezone.deactivate()

        return response 
Example #5
Source File: test_notifications.py    From linkedevents with MIT License 6 votes vote down vote up
def test_notification_template_format_datetime(notification_template):
    notification_template.body_en = "{{ datetime|format_datetime('en') }}"
    notification_template.save()

    dt = datetime(2020, 2, 22, 12, 0, 0, 0, pytz.utc)

    context = {
        'subject_var': 'bar',
        'datetime': dt,
        'html_body_var': 'foo <b>bar</b> baz',
    }

    timezone.activate(pytz.timezone('Europe/Helsinki'))

    rendered = render_notification_template(NotificationType.TEST, context, 'en')
    assert rendered['body'] == '22 Feb 2020 at 14:00' 
Example #6
Source File: test_notifications.py    From linkedevents with MIT License 6 votes vote down vote up
def test_notification_template_rendering_empty_html_body(notification_template):
    context = {
        'subject_var': 'bar',
        'body_var': 'baz',
        'html_body_var': 'foo <b>bar</b> baz',
    }

    activate('fi')
    notification_template.html_body = ''
    notification_template.save()

    rendered = render_notification_template(NotificationType.TEST, context, 'fi')
    assert len(rendered) == 3
    assert rendered['subject'] == "testiotsikko, muuttujan arvo: bar!"
    assert rendered['body'] == "testiruumis, muuttujan arvo: baz!"
    assert rendered['html_body'] == "" 
Example #7
Source File: test_notifications.py    From linkedevents with MIT License 6 votes vote down vote up
def test_notification_template_rendering_empty_text_body(notification_template):
    context = {
        'subject_var': 'bar',
        'body_var': 'baz',
        'html_body_var': 'foo <b>bar</b> baz',
    }

    activate('fi')
    notification_template.body = ''
    notification_template.save()

    rendered = render_notification_template(NotificationType.TEST, context, 'fi')
    assert len(rendered) == 3
    assert rendered['subject'] == "testiotsikko, muuttujan arvo: bar!"
    assert rendered['body'] == "testihötömölöruumis, muuttujan arvo: foo bar baz!"
    assert rendered['html_body'] == "testi<b>hötömölö</b>ruumis, muuttujan arvo: foo <b>bar</b> baz!" 
Example #8
Source File: views.py    From anytask with MIT License 6 votes vote down vote up
def profile_settings(request):
    user = request.user
    user_profile = user.profile

    if request.method == 'POST':
        user_profile.show_email = 'show_email' in request.POST
        user_profile.send_my_own_events = 'send_my_own_events' in request.POST
        user_profile.location = request.POST.get('location', '')
        if 'geoid' in request.POST:
            tz = get_tz(request.POST['geoid'])
            user_profile.time_zone = tz
            request.session['django_timezone'] = tz
            timezone.activate(pytz.timezone(tz))
        user_profile.save()

        return HttpResponse("OK")

    context = {
        'user_profile': user_profile,
        'geo_suggest_url': settings.GEO_SUGGEST_URL
    }

    return render(request, 'user_settings.html', context) 
Example #9
Source File: timezone.py    From goals.zone with GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, request):
        if "HTTP_X_FORWARDED_FOR" in request.META:
            request.META["HTTP_X_PROXY_REMOTE_ADDR"] = request.META["REMOTE_ADDR"]
            parts = request.META["HTTP_X_FORWARDED_FOR"].split(",", 1)
            request.META["REMOTE_ADDR"] = parts[0]
        ip = request.META["REMOTE_ADDR"]
        g = GeoIP2()
        try:
            ip_response = g.city(ip)
            time_zone = ip_response['time_zone']
        except AddressNotFoundError:
            time_zone = None
        if time_zone:
            timezone_object = pytz.timezone(time_zone)
            timezone.activate(timezone_object)
        else:
            timezone.deactivate()
        return self.get_response(request) 
Example #10
Source File: middleware.py    From devops with MIT License 5 votes vote down vote up
def process_request(self, request):
        try:
            account = getattr(request.user, "account", None)
        except Account.DoesNotExist:
            pass
        else:
            if account:
                tz = settings.TIME_ZONE if not account.timezone else account.timezone
                timezone.activate(tz) 
Example #11
Source File: timezone.py    From connect with MIT License 5 votes vote down vote up
def process_request(self, request):
        """Process the request and set the timezone."""
        if request.user.is_authenticated():
            if request.user.timezone:
                timezone.activate(pytz.timezone(request.user.timezone)) 
Example #12
Source File: timezone_middleware.py    From iguana with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def process_request(self, request):
        if request.user.is_authenticated:
            if request.user.timezone is not None:
                timezone.activate(pytz.timezone(request.user.timezone))
            else:
                timezone.activate(pytz.timezone('UTC'))
        else:
            timezone.deactivate() 
Example #13
Source File: timezone_middleware.py    From approval_frame with GNU General Public License v3.0 5 votes vote down vote up
def process_request(self, request):
        tzname = request.session.get('django_timezone')
        if tzname:
            timezone.activate(tzname)
        else:
            timezone.deactivate() 
Example #14
Source File: middleware.py    From diting with GNU General Public License v2.0 5 votes vote down vote up
def __call__(self, request):
        tzname = request.META.get('TZ')
        if tzname:
            timezone.activate(pytz.timezone(tzname))
        else:
            timezone.deactivate()
        response = self.get_response(request)
        return response 
Example #15
Source File: middleware.py    From devops with MIT License 5 votes vote down vote up
def process_request(self, request):
        translation.activate(self.get_language_for_user(request))
        request.LANGUAGE_CODE = translation.get_language() 
Example #16
Source File: middleware.py    From logtacts with MIT License 5 votes vote down vote up
def process_request(self, request):
        timezone.activate(pytz.timezone('America/Los_Angeles')) 
Example #17
Source File: middleware.py    From colossus with MIT License 5 votes vote down vote up
def __call__(self, request):
        if request.user.is_authenticated:
            try:
                timezone.activate(pytz.timezone(request.user.timezone))
            except UnknownTimeZoneError:
                timezone.deactivate()

        response = self.get_response(request)
        return response 
Example #18
Source File: middleware.py    From moolah with GNU General Public License v3.0 5 votes vote down vote up
def process_request(self, *args):
        timezone.activate(pytz.timezone('America/Chicago')) 
Example #19
Source File: test_timezone.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
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() 
Example #20
Source File: test_timezone.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_activate_invalid_timezone(self):
        with self.assertRaisesMessage(ValueError, 'Invalid timezone: None'):
            timezone.activate(None) 
Example #21
Source File: test_timezone.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
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() 
Example #22
Source File: test_viewsets_courses.py    From richie with MIT License 5 votes vote down vote up
def setUp(self):
        """
        Make sure all our tests are timezone-agnostic. Some of them parse ISO datetimes and those
        would be broken if we did not enforce timezone normalization.
        """
        super().setUp()
        timezone.activate(pytz.utc) 
Example #23
Source File: middleware.py    From esdc-ce with Apache License 2.0 5 votes vote down vote up
def process_request(self, request):
        tz = request.session.get(settings.TIMEZONE_SESSION_KEY)
        if not tz:
            tz = settings.TIME_ZONE
        timezone.activate(tz) 
Example #24
Source File: middleware.py    From avos with Apache License 2.0 5 votes vote down vote up
def _check_has_timed_timeout(self, request):
        """Check for session timeout and return timestamp."""
        has_timed_out = False
        # Activate timezone handling
        tz = request.session.get('django_timezone')
        if tz:
            timezone.activate(tz)
        try:
            timeout = settings.SESSION_TIMEOUT
        except AttributeError:
            timeout = 1800
        last_activity = request.session.get('last_activity', None)
        timestamp = int(time.time())
        if (
            hasattr(request, "user")
            and hasattr(request.user, "token")
            and not auth_utils.is_token_valid(request.user.token)
        ):
            # The user was logged in, but his keystone token expired.
            has_timed_out = True
        if isinstance(last_activity, int):
            if (timestamp - last_activity) > timeout:
                has_timed_out = True
            if has_timed_out:
                request.session.pop('last_activity')
        return (has_timed_out, timestamp) 
Example #25
Source File: middleware.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def process_request(self, request):
        try:
            tzname = request.user.wagtail_userprofile.current_time_zone
        except AttributeError:
            tzname = None
        if tzname:
            timezone.activate(pytz.timezone(tzname))
        else:
            timezone.deactivate() 
Example #26
Source File: test_multiday_event.py    From ls.joyous with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        timezone.activate("Pacific/Auckland") 
Example #27
Source File: i18n.py    From timestrap with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def process_request(self, request):
        tzname = get_site_setting("i18n_timezone")
        if tzname:
            timezone.activate(pytz.timezone(tzname))
        else:
            timezone.deactivate() 
Example #28
Source File: timezone.py    From brutaldon with GNU Affero General Public License v3.0 5 votes vote down vote up
def process_request(self, request):
        tzname = request.session.get("timezone", "UTC")
        if tzname:
            timezone.activate(pytz.timezone(tzname))
        else:
            timezone.deactivate() 
Example #29
Source File: middleware.py    From horas with MIT License 5 votes vote down vote up
def process_request(self, request):
        tzname = request.session.get("django_timezone")

        if tzname:
            timezone.activate(pytz.timezone(tzname))

        elif request.user.is_authenticated:
            try:
                tzname = request.user.timezone
                timezone.activate(pytz.timezone(tzname))
            except Exception as e:
                print("Failed to set timezone", e)
        else:
            timezone.deactivate() 
Example #30
Source File: middleware.py    From janeway with GNU Affero General Public License v3.0 5 votes vote down vote up
def process_request(self, request):
        if request.user.is_authenticated and request.user.preferred_timezone:
            tzname = request.user.preferred_timezone
        elif request.session.get("janeway_timezone"):
            tzname = request.session["janeway_timezone"]
        else:
            tzname = None

        try:
            request.timezone = tzname
            if tzname is not None:
                timezone.activate(pytz.timezone(tzname))
                logger.debug("Activated timezone %s" % tzname)
        except Exception as e:
            logger.warning("Failed to activate timezone %s: %s" % (tzname, e))