Ejemplo n.º 1
0
    def process_request(self, request):
        """
        Attempts to activate a timezone from a cookie or session
        """
        if getattr(settings, 'USE_TZ'):
            # check the cookie and the session
            tz = request.COOKIES.get('timezone')
            session_tz = request.session.get('timezone')
            tz = tz or session_tz

            if tz:
                try:
                    # attempt to activate the timezone. This might be an invalid
                    # timezone or none, so the rest of the logic following is coniditional
                    # on getting a valid timezone
                    timezone.activate(tz)

                    # caching the timezone inside the user instance
                    request.user._timezone = tz

                    # check to see if the session needs to be updated
                    if request.user.is_authenticated() and session_tz != tz:
                        request.session['timezone'] = tz
                        request.session.save()

                        # the session had to change, lets update the users database entry
                        # to be safe
                        tz_store, created = TimezoneStore.objects.get_or_create(user = request.user)
                        tz_store.timezone = tz
                        tz_store.save()

                except UnknownTimeZoneError:
                    pass
            else:
                timezone.deactivate()
    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
Ejemplo n.º 3
0
 def test_timestamp_utc_read(self):
     # Regression test for https://github.com/learningequality/kolibri/issues/1602
     timezone.activate(pytz.utc)
     obj = DateTimeTzModel.objects.create(timestamp=aware_datetime())
     obj.refresh_from_db()
     self.assertEqual(obj.timestamp, aware_datetime())
     timezone.deactivate()
Ejemplo n.º 4
0
 def test_timestamp_arbitrary_parse(self):
     tz = pytz.timezone('Africa/Nairobi')
     timezone.activate(tz)
     field = DateTimeTzSerializerField()
     timestamp = aware_datetime()
     self.assertEqual(field.to_internal_value(timestamp.isoformat()).tzinfo, aware_datetime().tzinfo)
     timezone.deactivate()
Ejemplo n.º 5
0
    def process_request(self, request):
        url = resolve(request.path_info)
        if 'event' in url.kwargs and 'organizer' in url.kwargs:
            try:
                request.event = Event.objects.get(
                    slug=url.kwargs['event'],
                    organizer__slug=url.kwargs['organizer'],
                )
            except Event.DoesNotExist:
                pass

        language = get_language_from_request(request)
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language()

        tzname = None
        if request.user.is_authenticated():
            tzname = request.user.timezone
        if hasattr(request, 'event'):
            tzname = request.event.timezone
        if tzname:
            try:
                timezone.activate(pytz.timezone(tzname))
            except pytz.UnknownTimeZoneError:
                pass
        else:
            timezone.deactivate()
Ejemplo n.º 6
0
def getDataLastHrs(req, hours):
    response = {}

    tz = req.GET.get('timezone', None)
    if tz is not None:
        timezone.activate(tz)
    else:
        timezone.activate(thermoctrl.settings.TIME_ZONE)

    # Calculate the range for today
    end = timezone.now()
    start = end - timedelta(hours=int(hours))

    entries = Temp.objects.filter(time__range=[start, end])
    response['status'] = 'success'
    response['numEntries'] = len(entries)

    response['entries'] = []
    for e in entries:
        # Localize the time into the end user's timezone.
        zone = timezone.get_current_timezone()
        localTime = e.time.astimezone(zone)

        response['entries'].append({
            "time_h": localTime.hour,
            "time_m": localTime.minute,
            "temp": e.temp
        })

    timezone.deactivate()

    return render_json(response)
Ejemplo n.º 7
0
 def process_request(self, request):
     if request.user.is_authenticated():
         tz = request.session.get('django_timezone',
                                  default=request.user.get_profile().time_zone) or settings.TIME_ZONE
         timezone.activate(tz)
     else:
         timezone.deactivate()
Ejemplo n.º 8
0
def entry_page(request, blog_slug, year, month, day, entry_slug):
    """
    View for rendering a blog entry page.

    Timezone changes notes:
    The URL provided to access the blog post represents the date in UTC.
    Making the query with the user timezone will cause missmatches.
    without activate: match tz_transform(UTC DB date, client_tz) with provided UTC url
    with activate: match UTC DB date with provided UTC url

    Date matching is not essential because the slug should be unique.
    """
    entry_qs = get_entries_queryset(request)
    try:
        django_timezone.activate(pytz.utc)
        entry = entry_qs.get(
            publication_date__year=year,
            publication_date__month=month,
            publication_date__day=day,
            slug=entry_slug, blog__slug=blog_slug,
            blog__entries_slugs_with_date=True)
    except BlogEntryPage.DoesNotExist:
        raise Http404
    finally:
        django_timezone.deactivate()

    return entry.render_to_response(request)
 def process_request(self, request):
     timezone.deactivate()
     if request.user and request.user.is_authenticated():
         tzname = request.user.time_zone
         if tzname:
             timezone.activate(pytz.timezone(tzname))
     return None
Ejemplo n.º 10
0
 def process_request(self, request):
     tzname = request.session.get('django_timezone')
     if tzname:
         #pass
         timezone.activate(pytz.timezone(tzname))
     else:
         timezone.deactivate()
Ejemplo n.º 11
0
 def process_request(self, request):
     if request.user.is_authenticated():
         tz = request.user.profile.timezone
         if tz:
             timezone.activate(tz)
         else:
             timezone.deactivate()
Ejemplo n.º 12
0
def get_message(user, user_type, issue, events, from_email, domain):
    user_profile = user.get_profile()

    if not user_profile.send_my_own_events:
        events = events.exclude(author_id=user.id)

    if not events:
        return ()

    lang = user_profile.language
    translation.activate(lang)
    timezone.activate(user_profile.time_zone)

    subject = (_(u'kurs') + u': {0} | ' + _(u'zadacha') + u': {1} | ' + _(u'student') + u': {2} {3}'). \
        format(issue.task.course.name, issue.task.get_title(lang), issue.student.last_name, issue.student.first_name)

    context = {
        "user": user,
        "domain": domain,
        "title": subject,
        "user_type": user_type,
        "issue": issue,
        "events": events,
        "STATIC_URL": settings.STATIC_URL,
    }

    plain_text = render_to_string('email_issue_notification.txt', context)
    html = render_to_string('email_issue_notification.html', context)
    translation.deactivate()
    timezone.deactivate()

    return subject, plain_text, html, from_email, [user.email]
Ejemplo n.º 13
0
    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()
Ejemplo n.º 14
0
    def process_request(self, request: HttpRequest):
        language = get_language_from_request(request)
        # Normally, this middleware runs *before* the event is set. However, on event frontend pages it
        # might be run a second time by pretix.presale.EventMiddleware and in this case the event is already
        # set and can be taken into account for the decision.
        if hasattr(request, 'event') and not request.path.startswith(get_script_prefix() + 'control'):
            if language not in request.event.settings.locales:
                firstpart = language.split('-')[0]
                if firstpart in request.event.settings.locales:
                    language = firstpart
                else:
                    language = request.event.settings.locale
                    for lang in request.event.settings.locales:
                        if lang.startswith(firstpart + '-'):
                            language = lang
                            break
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language()

        tzname = None
        if hasattr(request, 'event'):
            tzname = request.event.settings.timezone
        elif request.user.is_authenticated:
            tzname = request.user.timezone
        if tzname:
            try:
                timezone.activate(pytz.timezone(tzname))
                request.timezone = tzname
            except pytz.UnknownTimeZoneError:
                pass
        else:
            timezone.deactivate()
Ejemplo n.º 15
0
    def process_request(self, request):
        language = get_language_from_request(request)
        if hasattr(request, 'event') and not request.path.startswith(get_script_prefix() + 'control'):
            if language not in request.event.settings.locales:
                firstpart = language.split('-')[0]
                if firstpart in request.event.settings.locales:
                    language = firstpart
                else:
                    language = request.event.settings.locale
                    for lang in request.event.settings.locales:
                        if lang == firstpart or lang.startswith(firstpart + '-'):
                            language = lang
                            break
        translation.activate(language)
        request.LANGUAGE_CODE = translation.get_language()

        tzname = None
        if request.user.is_authenticated():
            tzname = request.user.timezone
        if hasattr(request, 'event'):
            tzname = request.event.settings.timezone
        if tzname:
            try:
                timezone.activate(pytz.timezone(tzname))
                request.timezone = tzname
            except pytz.UnknownTimeZoneError:
                pass
        else:
            timezone.deactivate()
Ejemplo n.º 16
0
 def test_default_arbitrary_create(self):
     tz = pytz.timezone('Africa/Nairobi')
     timezone.activate(tz)
     timestamp = aware_datetime()
     obj = DateTimeTzModel.objects.create()
     self.assertEqual(obj.default_timestamp.tzinfo, timestamp.tzinfo)
     timezone.deactivate()
Ejemplo n.º 17
0
 def process_request(self, request):
     tzname = request.session.get('django_timezone')
     if tzname:
         timezone.activate(pytz.timezone(tzname))
         print "TimeZone activated: ", tzname
     else:
         timezone.deactivate()
         print "tzname = ", tzname
Ejemplo n.º 18
0
 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
Ejemplo n.º 19
0
 def process_request(self, request):
     try:
         if request.user and hasattr(request.user, 'timezone') and request.user.timezone:
             timezone.activate(request.user.timezone)
         else:
             timezone.deactivate()
     except (exceptions.InvalidUserException, UnknownTimeZoneError):
         pass
Ejemplo n.º 20
0
 def process_request(self, request):
     try:
         if request.user.id and request.user.userprofile.tz:
             timezone.activate(pytz.timezone(request.user.userprofile.tz))
         else:
             timezone.deactivate()
     except UserProfile.DoesNotExist:
         timezone.deactivate()
Ejemplo n.º 21
0
 def test_timestamp_arbitrary_read(self):
     # Regression test for https://github.com/learningequality/kolibri/issues/1602
     tz = pytz.timezone('Africa/Nairobi')
     timezone.activate(tz)
     timestamp = aware_datetime()
     obj = DateTimeTzModel.objects.create(timestamp=timestamp)
     obj.refresh_from_db()
     self.assertEqual(obj.timestamp, timestamp)
     timezone.deactivate()
Ejemplo n.º 22
0
 def process_request(self, request):
     if request.user.is_authenticated():
         tzname = get_user_option(request.user, 'timezone')
     else:
         tzname = None
     if tzname:
         timezone.activate(pytz.timezone(tzname))
     else:
         timezone.deactivate()
    def setUp(self):
        super(TimezoneMiddlewareTest, self).setUp()
        self.tzm = TimezoneMiddleware()
        self.request = Mock()
        self.request.user = None
        self.UTC = timezone.get_default_timezone()

        # reset to default timezone
        timezone.deactivate()
Ejemplo n.º 24
0
    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
Ejemplo n.º 25
0
def activate_timezone(tz):
    """Activate Django timezone support if it is available.
    """
    try:
        from django.utils import timezone
        timezone.deactivate()
        timezone.activate(tz)
    except ImportError:
        pass
Ejemplo n.º 26
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     try:
         tz = request.account.get('timezone', request.site.get('timezone'))
     except AttributeError:
         tz = 'US/Eastern'
     if tz:
         timezone.activate(pytz.timezone(tz))
     else:
         timezone.deactivate()
Ejemplo n.º 27
0
 def process_request(self, request):
     try:
         tz = request.user.timezone
         if tz:
             timezone.activate(tz)
         else:
             timezone.deactivate()
     except AttributeError:
         timezone.deactivate()
Ejemplo n.º 28
0
 def process_request(self, request):
     tz = request.session.get('detected_tz')
     if tz:
         # `request.timezone_active` is used in the template
         # tag to detect if the timezone has been activated
         request.timezone_active = True
         timezone.activate(pytz.timezone(tz))
     else:
         timezone.deactivate()
Ejemplo n.º 29
0
 def process_request(self, request):
     request.session['django_timezone'] = 'Asia/Taipei'
     tzname = request.session.get('django_timezone')
     print 'Request From', ipHelper.get_client_ip(request), timezone.now()
     print 'Request With', request.META['HTTP_USER_AGENT']
     if tzname:
         timezone.activate(pytz.timezone(tzname))
     else:
         timezone.deactivate()
Ejemplo n.º 30
0
 def process_request(self, request):
     tzname = request.session.get('django_timezone')
     if hasattr(request,'user'):
     	if hasattr(request.user, 'studiouser'):
     		tzname = request.user.studiouser.studio_id.timezone
     if tzname:
         timezone.activate(pytz.timezone(tzname))
     else:
         timezone.deactivate()
Ejemplo n.º 31
0
 def process_request(self, request):
     tzname = gpm['Timezone__timezone']
     if tzname:
         timezone.activate(pytz.timezone(tzname))
     else:
         timezone.deactivate()
Ejemplo n.º 32
0
 def tearDown(self):
     timezone.deactivate()
Ejemplo n.º 33
0
 def process_request(self, request):
     tzname = request.session.get(settings.TIMEZONE_SESSION_KEY)
     if tzname:
         timezone.activate(pytz.timezone(tzname))
     else:
         timezone.deactivate()
Ejemplo n.º 34
0
 def process_view(self, request, view_func, view_args, view_kwargs):
     tzname = request.session.get('blueking_timezone')
     if tzname:
         timezone.activate(pytz.timezone(tzname))
     else:
         timezone.deactivate()
Ejemplo n.º 35
0
 def process_request(self, request):
     if request.user.is_authenticated():
         timezone.activate(request.user.timezone)
     else:
         timezone.deactivate()
Ejemplo n.º 36
0
def run(scheduled_process: ScheduledProcess) -> None:
    retention_settings = RetentionSettings.get_solo()

    if retention_settings.data_retention_in_hours == RetentionSettings.RETENTION_NONE:
        scheduled_process.disable()  # Changing the retention settings in the admin will re-activate it again.
        return

    # These models should be rotated with retention. Dict value is the datetime field used.
    ITEM_COUNT_PER_HOUR = 2
    MODELS_TO_CLEANUP = {
        DsmrReading.objects.processed(): 'timestamp',
        ElectricityConsumption.objects.all(): 'read_at',
        GasConsumption.objects.all(): 'read_at',
    }

    retention_date = timezone.now() - timezone.timedelta(hours=retention_settings.data_retention_in_hours)
    data_to_clean_up = False

    # We need to force UTC here, to avoid AmbiguousTimeError's on DST changes.
    timezone.activate(pytz.UTC)

    for base_queryset, datetime_field in MODELS_TO_CLEANUP.items():
        hours_to_cleanup = base_queryset.filter(
            **{'{}__lt'.format(datetime_field): retention_date}
        ).annotate(
            item_hour=TruncHour(datetime_field)
        ).values('item_hour').annotate(
            item_count=Count('id')
        ).order_by().filter(
            item_count__gt=ITEM_COUNT_PER_HOUR
        ).order_by('item_hour').values_list(
            'item_hour', flat=True
        )[:settings.DSMRREADER_RETENTION_MAX_CLEANUP_HOURS_PER_RUN]

        hours_to_cleanup = list(hours_to_cleanup)  # Force evaluation.

        if not hours_to_cleanup:
            continue

        data_to_clean_up = True

        for current_hour in hours_to_cleanup:
            # Fetch all data per hour.
            data_set = base_queryset.filter(
                **{
                    '{}__gte'.format(datetime_field): current_hour,
                    '{}__lt'.format(datetime_field): current_hour + timezone.timedelta(hours=1),
                }
            )

            # Extract the first/last item, so we can exclude it.
            # NOTE: Want to alter this? Please update ITEM_COUNT_PER_HOUR above as well!
            keeper_pks = [
                data_set.order_by(datetime_field)[0].pk,
                data_set.order_by('-{}'.format(datetime_field))[0].pk
            ]

            # Now drop all others.
            logger.debug('Retention: Cleaning up: %s (%s)', current_hour, data_set[0].__class__.__name__)
            data_set.exclude(pk__in=keeper_pks).delete()

    timezone.deactivate()

    # Delay for a bit, as there is nothing to do.
    if not data_to_clean_up:
        scheduled_process.delay(hours=12)
Ejemplo n.º 37
0
 def test_default_utc_create(self):
     timezone.activate(pytz.utc)
     obj = DateTimeTzModel.objects.create()
     self.assertEqual(obj.default_timestamp.tzinfo, pytz.utc)
     timezone.deactivate()
Ejemplo n.º 38
0
 def process_request(self, request):
     tzname = request.session.get('django_timzone')
     if tzname:
         timezone.activiate(pytz.timezone(tzname))
     else:
         timezone.deactivate()
Ejemplo n.º 39
0
 def test_timestamp_utc_create(self):
     timezone.activate(pytz.utc)
     obj = DateTimeTzModel.objects.create(timestamp=aware_datetime())
     self.assertEqual(obj.timestamp.tzinfo, aware_datetime().tzinfo)
     timezone.deactivate()
Ejemplo n.º 40
0
import pytz
from django.http import HttpResponse
from django.utils import timezone
from django.utils.deprecation import MiddlewareMixin
from django.conf import settings


class HealthCheckMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.META["PATH_INFO"] == settings.HEALTH_CHECK_URL:
            return HttpResponse("pong")


class TimezoneMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if tzname := request.COOKIES.get(settings.TIMEZONE_COOKIE_NAME):
            timezone.activate(pytz.timezone(tzname))
        else:
            timezone.deactivate()
        return self.get_response(request)
Ejemplo n.º 41
0
def apply_data_retention():
    """
    When data retention is enabled, this discards all data applicable for retention. Keeps at least one data point per
    hour available.
    """
    retention_settings = RetentionSettings.get_solo()

    if retention_settings.data_retention_in_hours is None:
        # No retention enabled at all (default behaviour).
        return

    current_time = timezone.localtime(timezone.now())

    # Only cleanup during nights. Allow from midnight to six a.m.
    if current_time.hour >= settings.DSMRREADER_RETENTION_UNTIL_THIS_HOUR:
        return

    # These models should be rotated with retention. Dict value is the datetime field used.
    MODELS_TO_CLEANUP = {
        DsmrReading.objects.processed(): 'timestamp',
        ElectricityConsumption.objects.all(): 'read_at',
        GasConsumption.objects.all(): 'read_at',
    }

    retention_date = timezone.now() - timezone.timedelta(hours=retention_settings.data_retention_in_hours)

    # We need to force UTC here, to avoid AmbiguousTimeError's on DST changes.
    timezone.activate(pytz.UTC)

    for base_queryset, datetime_field in MODELS_TO_CLEANUP.items():
        hours_to_cleanup = base_queryset.filter(
            **{'{}__lt'.format(datetime_field): retention_date}
        ).annotate(
            item_hour=TruncHour(datetime_field)
        ).values('item_hour').annotate(
            item_count=Count('id')
        ).order_by().filter(
            item_count__gt=2
        ).order_by('item_hour').values_list(
            'item_hour', flat=True
        )[:settings.DSMRREADER_RETENTION_MAX_CLEANUP_HOURS_PER_RUN]

        hours_to_cleanup = list(hours_to_cleanup)  # Force evaluation.

        if not hours_to_cleanup:
            continue

        for current_hour in hours_to_cleanup:

            # Fetch all data per hour.
            data_set = base_queryset.filter(
                **{
                    '{}__gte'.format(datetime_field): current_hour,
                    '{}__lt'.format(datetime_field): current_hour + timezone.timedelta(hours=1),
                }
            )

            # Extract the first/last item, so we can exclude it.
            # NOTE: Want to alter this? Please update "item_count__gt=2" above as well!
            keeper_pks = [
                data_set.order_by(datetime_field)[0].pk,
                data_set.order_by('-{}'.format(datetime_field))[0].pk
            ]

            # Now drop all others.
            commands_logger.debug('Retention | Cleaning up: %s (%s)', current_hour, data_set[0].__class__.__name__)
            data_set.exclude(pk__in=keeper_pks).delete()

    timezone.deactivate()
Ejemplo n.º 42
0
 def __call__(self, request):
     timezone.deactivate()
     return self.get_response(request)
Ejemplo n.º 43
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     if self.timezone is None:
         timezone.deactivate()
     else:
         timezone.activate(self.timezone)
Ejemplo n.º 44
0
 def process_request(self, request):
     tzname = get_site_setting('i18n_timezone')
     if tzname:
         timezone.activate(pytz.timezone(tzname))
     else:
         timezone.deactivate()
Ejemplo n.º 45
0
 def process_request(self, request):
     tzname = request.META.get('TZ')
     if tzname:
         timezone.activate(pytz.timezone(tzname))
     else:
         timezone.deactivate()
Ejemplo n.º 46
0
 def process_request(self, request):
     user = request.user
     if user.is_authenticated() and hasattr(user, 'profile') and user.profile.timezone is not None:
         timezone.activate(pytz.timezone(user.profile.timezone))
     else:
         timezone.deactivate()
Ejemplo n.º 47
0
 def process_response(self, request, response):
     timezone.deactivate()
     return response
Ejemplo n.º 48
0
 def process_request(self, request):
     tzname = self._get_user_timezone(request)
     if tzname:
         timezone.activate(pytz.timezone(tzname))
     else:
         timezone.deactivate()
Ejemplo n.º 49
0
 def __exit__(self, type_name, value, traceback):
     if self.timezone:
         timezone.deactivate()
     if self.language:
         translation.deactivate()
Ejemplo n.º 50
0
def deactivate():
    from django.utils.timezone import deactivate
    deactivate()
Ejemplo n.º 51
0
def send_email_reminder(email, subject, reminder_id, calendar_item_id,
                        calendar_item_type):
    # The instance may no longer exist by the time this request is processed, in which case we can simply and safely
    # skip it
    try:
        reminder = Reminder.objects.get(pk=reminder_id)
    except Reminder.DoesNotExist:
        logger.info(
            'Reminder {} does not exist. Nothing to do.'.format(reminder_id))

        return

    if settings.DISABLE_EMAILS:
        logger.warning('Emails disabled. Reminder {} not being sent.'.format(
            reminder.pk))
        return

    try:
        if calendar_item_type == enums.EVENT:
            calendar_item = Event.objects.get(pk=calendar_item_id)
        elif calendar_item_type == enums.HOMEWORK:
            calendar_item = Homework.objects.get(pk=calendar_item_id)
        else:
            logger.info(
                'Nothing to do here, as a calendar_item_type of {} does not exist.'
                .format(calendar_item_type))

            return
    except (Event.DoesNotExist, Homework.DoesNotExist):
        logger.info(
            'calendar_item_id {} does not exist. Nothing to do.'.format(
                calendar_item_id))

        return

    timezone.activate(pytz.timezone(reminder.user.settings.time_zone))

    start = timezone.localtime(calendar_item.start).strftime(
        settings.NORMALIZED_DATE_FORMAT if calendar_item.all_day else settings.
        NORMALIZED_DATE_TIME_FORMAT)
    end = timezone.localtime(calendar_item.end).strftime(
        settings.NORMALIZED_DATE_FORMAT if calendar_item.all_day else settings.
        NORMALIZED_DATE_TIME_FORMAT)
    normalized_datetime = '{} to {}'.format(
        start, end) if calendar_item.show_end_time else start

    normalized_materials = None
    if reminder.homework:
        normalized_materials = calendar_item.materials.values_list('title',
                                                                   flat=True)
        normalized_materials = ', '.join(normalized_materials)

    comments = calendar_item.comments if calendar_item.comments.strip(
    ) != '' else None

    commonutils.send_multipart_email(
        'email/reminder', {
            'PROJECT_NAME': settings.PROJECT_NAME,
            'reminder': reminder,
            'calendar_item': calendar_item,
            'normalized_datetime': normalized_datetime,
            'normalized_materials': normalized_materials,
            'comments': comments,
        }, subject, [email])

    metricutils.increment('action.reminder.sent.email')

    timezone.deactivate()
Ejemplo n.º 52
0
 def process_request(self, request):
     tzname = request.session.get('timezone', "UTC")
     if tzname:
         timezone.activate(pytz.timezone(tzname))
     else:
         timezone.deactivate()
Ejemplo n.º 53
0
 def setUp(self):
     timezone.deactivate()
     utils.cache_clear()
     self.user = utils.create_user()