Python django.utils.timezone.override() Examples

The following are 30 code examples for showing how to use django.utils.timezone.override(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.utils.timezone , or try the search function .

Example 1
Project: karrot-backend   Author: yunity   File: tasks.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def daily_activity_notifications():

    with timer() as t:
        for group in Group.objects.all():
            with timezone.override(group.timezone):
                if timezone.localtime().hour != 20:  # only at 8pm local time
                    continue

                for data in fetch_activity_notification_data_for_group(group):
                    prepare_activity_notification_email(**data).send()
                    stats.activity_notification_email(
                        group=data['group'], **{k: v.count()
                                                for k, v in data.items() if isinstance(v, QuerySet)}
                    )

    stats_utils.periodic_task('activities__daily_activity_notifications', seconds=t.elapsed_seconds) 
Example 2
Project: karrot-backend   Author: yunity   File: tasks.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def notify_message_push_subscribers_with_language(message, subscriptions, language):
    conversation = message.conversation

    if not translation.check_for_language(language):
        language = 'en'

    with translation.override(language):
        message_title = get_message_title(message, language)

    if message.is_thread_reply():
        click_action = frontend_urls.thread_url(message.thread)
    else:
        click_action = frontend_urls.conversation_url(conversation, message.author)

    notify_subscribers_by_device(
        subscriptions,
        click_action=click_action,
        fcm_options={
            'message_title': message_title,
            'message_body': Truncator(message.content).chars(num=1000),
            # this causes each notification for a given conversation to replace previous notifications
            # fancier would be to make the new notifications show a summary not just the latest message
            'tag': 'conversation:{}'.format(conversation.id),
        }
    ) 
Example 3
Project: karrot-backend   Author: yunity   File: emails.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def prepare_application_message_notification(user, messages):
    application = target_from_messages(messages)
    with translation.override(language_for_user(user)):
        reply_to_name = application.user.display_name
        if application.user == user:
            conversation_name = _('New message in your application to %(group_name)s') % {
                'group_name': application.group.name
            }
        else:
            conversation_name = _('New message in application of %(user_name)s to %(group_name)s') % {
                'user_name': application.user.display_name,
                'group_name': application.group.name,
            }
        return prepare_message_notification(
            user,
            messages,
            reply_to_name=reply_to_name,
            group=application.group,
            conversation_name=conversation_name,
            conversation_url=application_url(application),
            stats_category='application_message'
        ) 
Example 4
Project: django-radio   Author: iago1460   File: views.py    License: GNU General Public License v3.0 6 votes vote down vote up
def now(self, request):
        data = TimezoneForm(request.query_params)
        if not data.is_valid():
            raise DRFValidationError(data.errors)
        requested_timezone = data.cleaned_data.get('timezone')

        tz = requested_timezone or pytz.utc
        now = utils.timezone.now()
        transmissions = Transmission.at(now)
        try:
            transmission = next(transmissions)
        except StopIteration:
            return Response(None)
        else:
            serializer = self.get_serializer(transmission, many=False)
            with override(timezone=tz):
                return Response(serializer.data) 
Example 5
Project: django-sqlserver   Author: denisenkom   File: tests.py    License: MIT License 6 votes vote down vote up
def test_get_current_timezone_templatetag(self):
        """
        Test the {% get_current_timezone %} templatetag.
        """
        tpl = Template("{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}")

        self.assertEqual(tpl.render(Context()), "Africa/Nairobi")
        with timezone.override(UTC):
            self.assertEqual(tpl.render(Context()), "UTC")

        tpl = Template(
            "{% load tz %}{% timezone tz %}{% get_current_timezone as time_zone %}"
            "{% endtimezone %}{{ time_zone }}"
        )

        self.assertEqual(tpl.render(Context({'tz': ICT})), "+0700")
        with timezone.override(UTC):
            self.assertEqual(tpl.render(Context({'tz': ICT})), "+0700") 
Example 6
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_current_timezone_templatetag(self):
        """
        Test the {% get_current_timezone %} templatetag.
        """
        tpl = Template("{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}")

        self.assertEqual(tpl.render(Context()), "Africa/Nairobi")
        with timezone.override(UTC):
            self.assertEqual(tpl.render(Context()), "UTC")

        tpl = Template(
            "{% load tz %}{% timezone tz %}{% get_current_timezone as time_zone %}"
            "{% endtimezone %}{{ time_zone }}"
        )

        self.assertEqual(tpl.render(Context({'tz': ICT})), "+0700")
        with timezone.override(UTC):
            self.assertEqual(tpl.render(Context({'tz': ICT})), "+0700") 
Example 7
Project: djongo   Author: nesdis   File: test_timezone.py    License: 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 8
Project: djongo   Author: nesdis   File: tests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_get_current_timezone_templatetag(self):
        """
        Test the {% get_current_timezone %} templatetag.
        """
        tpl = Template("{% load tz %}{% get_current_timezone as time_zone %}{{ time_zone }}")

        self.assertEqual(tpl.render(Context()), "Africa/Nairobi")
        with timezone.override(UTC):
            self.assertEqual(tpl.render(Context()), "UTC")

        tpl = Template(
            "{% load tz %}{% timezone tz %}{% get_current_timezone as time_zone %}"
            "{% endtimezone %}{{ time_zone }}"
        )

        self.assertEqual(tpl.render(Context({'tz': ICT})), "+0700")
        with timezone.override(UTC):
            self.assertEqual(tpl.render(Context({'tz': ICT})), "+0700") 
Example 9
Project: djongo   Author: nesdis   File: test_timezone.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_localdate(self):
        naive = datetime.datetime(2015, 1, 1, 0, 0, 1)
        with self.assertRaisesMessage(ValueError, 'localtime() cannot be applied to a naive datetime'):
            timezone.localdate(naive)
        with self.assertRaisesMessage(ValueError, 'localtime() cannot be applied to a naive datetime'):
            timezone.localdate(naive, timezone=EAT)

        aware = datetime.datetime(2015, 1, 1, 0, 0, 1, tzinfo=ICT)
        self.assertEqual(timezone.localdate(aware, timezone=EAT), datetime.date(2014, 12, 31))
        with timezone.override(EAT):
            self.assertEqual(timezone.localdate(aware), datetime.date(2014, 12, 31))

        with mock.patch('django.utils.timezone.now', return_value=aware):
            self.assertEqual(timezone.localdate(timezone=EAT), datetime.date(2014, 12, 31))
            with timezone.override(EAT):
                self.assertEqual(timezone.localdate(), datetime.date(2014, 12, 31)) 
Example 10
Project: GTDWeb   Author: lanbing510   File: tz.py    License: GNU General Public License v2.0 5 votes vote down vote up
def render(self, context):
        with timezone.override(self.tz.resolve(context)):
            output = self.nodelist.render(context)
        return output 
Example 11
Project: bioforum   Author: reBiocoder   File: tz.py    License: MIT License 5 votes vote down vote up
def render(self, context):
        with timezone.override(self.tz.resolve(context)):
            output = self.nodelist.render(context)
        return output 
Example 12
Project: karrot-backend   Author: yunity   File: emails.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def calculate_group_summary_dates(group):
    with timezone.override(group.timezone):
        tz = get_current_timezone()

        # midnight last night in the groups local timezone
        midnight = tz.localize(timezone.now().replace(tzinfo=None, hour=0, minute=0, second=0, microsecond=0))

        # 7 days before that
        from_date = midnight - relativedelta(days=7)

        # a week after from date
        to_date = from_date + relativedelta(days=7)

        return from_date, to_date 
Example 13
Project: karrot-backend   Author: yunity   File: test_tasks.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_summary_email_dates_printed_correctly(self):
        mail.outbox = []
        with timezone.override(timezone.utc), freeze_time(datetime.datetime(2018, 8, 19)):  # Sunday
            group = GroupFactory()
            self.make_activity_in_group(group)
            from_date, to_date = calculate_group_summary_dates(group)
            context = prepare_group_summary_data(group, from_date, to_date)
            emails = prepare_group_summary_emails(group, context)
            self.assertGreater(len(emails), 0)
            email = emails[0]
            expected_format = 'Sunday, August 12, 2018 to Saturday, August 18, 2018'
            self.assertIn(expected_format, email.body) 
Example 14
Project: karrot-backend   Author: yunity   File: test_tasks.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_summary_emails_send_at_8am_localtime(self):
        group = GroupFactory(timezone=pytz.timezone('Europe/Berlin'))
        # 6am UTC is 8am in this timezone
        with timezone.override(timezone.utc), freeze_time(datetime.datetime(2018, 8, 19, 6, 0, 0, tzinfo=pytz.utc)):
            self.make_activity_in_group(group)
            mail.outbox = []
            send_summary_emails()
            self.assertEqual(len(mail.outbox), self.new_user_count) 
Example 15
Project: karrot-backend   Author: yunity   File: test_tasks.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_summary_emails_do_not_send_at_other_times(self):
        group = GroupFactory(timezone=pytz.timezone('Europe/Berlin'))
        # 6am UTC is 8am in this timezone
        with timezone.override(timezone.utc), freeze_time(datetime.datetime(2018, 8, 19, 7, 0, 0, tzinfo=pytz.utc)):
            self.make_activity_in_group(group)
            mail.outbox = []
            send_summary_emails()
            self.assertEqual(len(mail.outbox), 0) 
Example 16
Project: karrot-backend   Author: yunity   File: test_email_utils.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_time_filter_uses_timezone(self):
        hour = 5
        datetime = timezone.now().replace(
            tzinfo=pytz.utc,
            hour=hour,
            minute=0,
            second=0,
            microsecond=0,
        )
        tz = pytz.timezone('Europe/Berlin')
        offset_hours = int(tz.utcoffset(datetime.utcnow()).total_seconds() / 3600)
        with timezone.override(tz), translation.override('en'):
            val = time_filter(datetime)
            self.assertEqual(val, '{}:00 AM'.format(hour + offset_hours)) 
Example 17
Project: karrot-backend   Author: yunity   File: email_utils.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def prepare_email_content(template, context, tz, language='en'):
    if not translation.check_for_language(language):
        language = 'en'

    with timezone.override(tz), translation.override(language):

        html_content = None

        try:
            html_template = get_template('{}.html.jinja2'.format(template))
            html_content = html_template.render(context)
        except TemplateDoesNotExist:
            pass

        try:
            text_template = get_template('{}.text.jinja2'.format(template))
            text_content = text_template.render(context)
        except TemplateDoesNotExist:
            if html_content:
                text_content = generate_plaintext_from_html(html_content)
            else:
                raise Exception('Nothing to use for text content, no text or html templates available.')

        subject = render_to_string('{}.subject.jinja2'.format(template), context).replace('\n', '')

        return subject, text_content, html_content 
Example 18
Project: karrot-backend   Author: yunity   File: test_tasks.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def group_timezone_at(group, **kwargs):
    with timezone.override(group.timezone):
        datetime = timezone.localtime(timezone=group.timezone).replace(**kwargs)
        with freeze_time(datetime, tick=True):
            yield 
Example 19
Project: karrot-backend   Author: yunity   File: emails.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def prepare_group_conversation_message_notification(user, message):
    conversation = message.conversation
    group = conversation.target
    reply_to_name = group.name
    conversation_name = group.name
    with translation.override(language_for_user(user)):
        return prepare_message_notification(
            user,
            messages=[message],
            group=group,
            reply_to_name=reply_to_name,
            conversation_name=conversation_name,
            conversation_url=group_wall_url(group),
            stats_category='group_conversation_message'
        ) 
Example 20
Project: karrot-backend   Author: yunity   File: emails.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def prepare_place_conversation_message_notification(user, message):
    conversation = message.conversation
    place = conversation.target
    reply_to_name = place.name
    conversation_name = place.name
    with translation.override(language_for_user(user)):
        return prepare_message_notification(
            user,
            messages=[message],
            group=place.group,
            reply_to_name=reply_to_name,
            conversation_name=conversation_name,
            conversation_url=place_wall_url(place),
            stats_category='place_conversation_message'
        ) 
Example 21
Project: karrot-backend   Author: yunity   File: emails.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def prepare_activity_conversation_message_notification(user, messages):
    activity = target_from_messages(messages)
    language = language_for_user(user)
    with translation.override(language):
        with timezone.override(activity.place.group.timezone):
            weekday = format_date(
                activity.date.start.astimezone(timezone.get_current_timezone()),
                'EEEE',
                locale=translation.to_locale(language),
            )
            time = format_time(
                activity.date.start,
                format='short',
                locale=translation.to_locale(language),
                tzinfo=timezone.get_current_timezone(),
            )
            date = format_date(
                activity.date.start.astimezone(timezone.get_current_timezone()),
                format='long',
                locale=translation.to_locale(language),
            )

            long_date = '{} {}, {}'.format(weekday, time, date)
            short_date = '{} {}'.format(weekday, time)

            reply_to_name = _('Pickup %(date)s') % {
                'date': short_date,
            }
            conversation_name = _('Pickup %(date)s') % {
                'date': long_date,
            }

        return prepare_message_notification(
            user,
            messages,
            group=activity.place.group,
            reply_to_name=reply_to_name,
            conversation_name=conversation_name,
            conversation_url=activity_detail_url(activity),
            stats_category='activity_conversation_message'
        ) 
Example 22
Project: karrot-backend   Author: yunity   File: emails.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def prepare_private_user_conversation_message_notification(user, messages):
    with translation.override(language_for_user(user)):
        first_message = messages[0]
        author = first_message.author
        return prepare_message_notification(
            user,
            messages,
            conversation_name=author.display_name,
            conversation_url=user_detail_url(author),
            stats_category='private_conversation_message'
        ) 
Example 23
Project: karrot-backend   Author: yunity   File: emails.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def prepare_offer_message_notification(user, messages):
    offer = target_from_messages(messages)
    with translation.override(language_for_user(user)):
        return prepare_message_notification(
            user,
            messages,
            group=offer.group,
            conversation_name=_('New message for offer %(offer_name)s in %(group_name)s') % {
                'offer_name': offer.name,
                'group_name': offer.group.name,
            },
            conversation_url=offer_url(offer),
            stats_category='offer_message'
        ) 
Example 24
Project: django-radio   Author: iago1460   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def list(self, request, *args, **kwargs):
        data = TransmissionForm(request.query_params)
        if not data.is_valid():
            raise DRFValidationError(data.errors)
        requested_timezone = data.cleaned_data.get('timezone')

        after = data.cleaned_data['after']
        before = data.cleaned_data['before']

        tz = requested_timezone or pytz.utc
        after_date = tz.localize(datetime.datetime.combine(after, datetime.time()))
        before_date = tz.localize(datetime.datetime.combine(before, datetime.time(23, 59, 59)))

        # Apply filters to the queryset
        schedules = self.filter_queryset(self.get_queryset())
        # Filter by active calendar if that filter was not provided
        if not data.cleaned_data.get('calendar'):
            schedules = schedules.filter(calendar__is_active=True)

        transmissions = Transmission.between(
            after_date,
            before_date,
            schedules=schedules
        )
        serializer = self.get_serializer(transmissions, many=True)
        with override(timezone=tz):
            return Response(serializer.data) 
Example 25
Project: online-judge   Author: DMOJ   File: timezone.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __call__(self, request):
        with timezone.override(self.get_timezone(request)):
            return self.get_response(request) 
Example 26
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: tz.py    License: MIT License 5 votes vote down vote up
def render(self, context):
        with timezone.override(self.tz.resolve(context)):
            output = self.nodelist.render(context)
        return output 
Example 27
Project: python   Author: Yeah-Kun   File: tz.py    License: Apache License 2.0 5 votes vote down vote up
def render(self, context):
        with timezone.override(self.tz.resolve(context)):
            output = self.nodelist.render(context)
        return output 
Example 28
Project: luscan-devel   Author: blackye   File: tz.py    License: GNU General Public License v2.0 5 votes vote down vote up
def render(self, context):
        with timezone.override(self.tz.resolve(context)):
            output = self.nodelist.render(context)
        return output 
Example 29
Project: openhgsenti   Author: drexly   File: tz.py    License: Apache License 2.0 5 votes vote down vote up
def render(self, context):
        with timezone.override(self.tz.resolve(context)):
            output = self.nodelist.render(context)
        return output 
Example 30
Project: python2017   Author: bpgc-cte   File: tz.py    License: MIT License 5 votes vote down vote up
def render(self, context):
        with timezone.override(self.tz.resolve(context)):
            output = self.nodelist.render(context)
        return output