Skip to content
This repository has been archived by the owner on Feb 26, 2024. It is now read-only.

Commit

Permalink
Make usage of django-timezone more explicit in code
Browse files Browse the repository at this point in the history
The `timezone` module name is very ambiguous within Django, so whereever
we use django-timezone's `timezone` module make it clearer by naming it
`djtz`.
  • Loading branch information
jmurty committed Oct 18, 2016
1 parent cf8d40e commit 77f2cb7
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 60 deletions.
14 changes: 7 additions & 7 deletions icekit_events/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from icekit.admin import (
ChildModelFilter, ChildModelPluginPolymorphicParentModelAdmin)
from polymorphic.admin import PolymorphicChildModelAdmin
from timezone import timezone
from timezone import timezone as djtz # django-timezone

from icekit.publishing import admin as publishing_admin

Expand Down Expand Up @@ -176,12 +176,12 @@ def calendar_data(self, request):
to be loaded in an iframe.
"""
if 'timezone' in request.GET:
tz = timezone.get(request.GET.get('timezone'))
tz = djtz.get(request.GET.get('timezone'))
else:
tz = get_current_timezone()
start = timezone.localize(
start = djtz.localize(
datetime.datetime.strptime(request.GET['start'], '%Y-%m-%d'), tz)
end = timezone.localize(
end = djtz.localize(
datetime.datetime.strptime(request.GET['end'], '%Y-%m-%d'), tz)

all_occurrences = models.Occurrence.objects.draft().overlapping(start, end)
Expand Down Expand Up @@ -210,8 +210,8 @@ def _calendar_json_for_occurrence(self, occurrence):
# included in the calendar.
end = occurrence.start + timedelta(days=1)
else:
start = timezone.localize(occurrence.start)
end = timezone.localize(occurrence.end)
start = djtz.localize(occurrence.start)
end = djtz.localize(occurrence.end)
if occurrence.is_cancelled and occurrence.cancel_reason:
title = u"{0} [{1}]".format(
occurrence.event.title, occurrence.cancel_reason)
Expand Down Expand Up @@ -288,7 +288,7 @@ def preview(self, request):
limit = int(request.POST.get('limit', 10))
try:
rruleset = rrule.rrulestr(
recurrence_rule, dtstart=timezone.now(), forceset=True)
recurrence_rule, dtstart=djtz.now(), forceset=True)
except ValueError as e:
data = {
'error': six.text_type(e),
Expand Down
29 changes: 14 additions & 15 deletions icekit_events/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from dateutil import rrule
import six
import pytz
from timezone import timezone
from timezone import timezone as djtz # django-timezone

from django.core.urlresolvers import reverse
from django.conf import settings
Expand All @@ -22,7 +22,6 @@
get_current_timezone

from polymorphic.models import PolymorphicModel
from timezone.timezone import localize, now

from icekit.content_collections.abstract_models import AbstractListingPage, \
TitleSlugMixin
Expand All @@ -31,7 +30,7 @@
from icekit.publishing.middleware import is_draft_request_context
from django.template.defaultfilters import date as datefilter

from . import appsettings, validators, utils
from . import appsettings, validators
from .utils import timeutils


Expand All @@ -57,7 +56,7 @@ def zero_datetime(dt, tz=None):

def default_starts():
when = timeutils.round_datetime(
when=timezone.now(),
when=djtz.now(),
precision=appsettings.DEFAULT_STARTS_PRECISION,
rounding=timeutils.ROUND_UP,
)
Expand All @@ -69,7 +68,7 @@ def default_ends():


def default_date_starts():
return timezone.date()
return djtz.date()


def default_date_ends():
Expand Down Expand Up @@ -161,9 +160,9 @@ class AbstractBaseModel(models.Model):
"""

created = models.DateTimeField(
default=timezone.now, db_index=True, editable=False)
default=djtz.now, db_index=True, editable=False)
modified = models.DateTimeField(
default=timezone.now, db_index=True, editable=False)
default=djtz.now, db_index=True, editable=False)

class Meta:
abstract = True
Expand All @@ -174,7 +173,7 @@ def save(self, *args, **kwargs):
"""
Update ``self.modified``.
"""
self.modified = timezone.now()
self.modified = djtz.now()
super(AbstractBaseModel, self).save(*args, **kwargs)


Expand Down Expand Up @@ -526,7 +525,7 @@ def generate(self, until=None):
if self.repeat_end:
until = self.repeat_end
else:
until = timezone.now() + appsettings.REPEAT_LIMIT
until = djtz.now() + appsettings.REPEAT_LIMIT
# Make datetimes naive, since RRULE spec contains naive datetimes so
# our constraints must be the same
start_dt = coerce_naive(start_dt)
Expand Down Expand Up @@ -560,7 +559,7 @@ def _build_complete_rrule(self, start_dt=None, until=None):
start_dt = self.start
if until is None:
until = self.repeat_end \
or timezone.now() + appsettings.REPEAT_LIMIT
or djtz.now() + appsettings.REPEAT_LIMIT
# We assume `recurrence_rule` is always a RRULE repeat spec of the form
# "FREQ=DAILY", "FREQ=WEEKLY", etc?
rrule_spec = "DTSTART:%s" % format_naive_ical_dt(start_dt)
Expand Down Expand Up @@ -755,11 +754,11 @@ def __str__(self):

@property
def local_start(self):
return localize(self.start)
return djtz.localize(self.start)

@property
def local_end(self):
return localize(self.end)
return djtz.localize(self.end)

@property
def is_generated(self):
Expand Down Expand Up @@ -802,7 +801,7 @@ def is_past(self):
"""
:return: True if this occurrence is entirely in the past
"""
return self.end < now()
return self.end < djtz.now()

def get_absolute_url(self):
return self.event.get_absolute_url()
Expand Down Expand Up @@ -849,9 +848,9 @@ class Meta:

def get_start(self, request):
try:
start = timezone.parse('%s 00:00' % request.GET.get('date'))
start = djtz.parse('%s 00:00' % request.GET.get('date'))
except ValueError:
start = timezone.midnight()
start = djtz.midnight()
return start

def get_days(self, request):
Expand Down
63 changes: 28 additions & 35 deletions icekit_events/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

# WebTest API docs: http://webtest.readthedocs.org/en/latest/api.html

from timezone import timezone
from timezone import timezone as djtz # django-timezone
from datetime import datetime, timedelta, time
import six
import json
Expand All @@ -19,14 +19,13 @@
from django.forms.models import fields_for_model
from django.test import TestCase
from django.test.utils import override_settings
from django.utils.timezone import make_naive

from django_dynamic_fixture import G
from django_webtest import WebTest

from icekit_events import appsettings, forms, models
from icekit_events.event_types.simple.models import SimpleEvent
from icekit_events.models import get_occurrence_times_for_event
from icekit_events.models import get_occurrence_times_for_event, coerce_naive
from icekit_events.utils import timeutils


Expand All @@ -41,7 +40,7 @@ def setUp(self):
)
self.superuser.set_password('abc123')
self.start = timeutils.round_datetime(
when=timezone.now(),
when=djtz.now(),
precision=timedelta(minutes=1),
rounding=timeutils.ROUND_DOWN)
self.end = self.start + timedelta(minutes=45)
Expand Down Expand Up @@ -275,9 +274,9 @@ def test_event_with_repeatsgenerators_and_user_modified_occurrences(self):
#######################################################################
form = response.forms[0]
extra_occurrence_start = (first_occurrence.start - timedelta(days=3)) \
.astimezone(timezone.get_current_timezone())
.astimezone(djtz.get_current_timezone())
extra_occurrence_end = (first_occurrence.end - timedelta(days=3)) \
.astimezone(timezone.get_current_timezone())
.astimezone(djtz.get_current_timezone())
form['occurrences-10-start_0'].value = \
extra_occurrence_start.strftime('%Y-%m-%d')
form['occurrences-10-start_1'].value = \
Expand All @@ -303,7 +302,7 @@ def test_event_with_repeatsgenerators_and_user_modified_occurrences(self):
self.assertFalse(shifted_occurrence.is_user_modified)
shifted_occurrence_start = \
(shifted_occurrence.start + timedelta(minutes=30)) \
.astimezone(timezone.get_current_timezone())
.astimezone(djtz.get_current_timezone())
form['occurrences-6-start_0'].value = \
shifted_occurrence_start.strftime('%Y-%m-%d')
form['occurrences-6-start_1'].value =\
Expand Down Expand Up @@ -449,7 +448,7 @@ def test_event_publishing(self):
repeat_end.strftime('%H:%M:%S')
# Add ad-hoc occurrence
extra_occurrence_start = (self.start - timedelta(days=30)) \
.astimezone(timezone.get_current_timezone())
.astimezone(djtz.get_current_timezone())
extra_occurrence_end = extra_occurrence_start + timedelta(hours=3)
form['occurrences-0-start_0'].value = \
extra_occurrence_start.strftime('%Y-%m-%d')
Expand Down Expand Up @@ -601,7 +600,7 @@ def test_admin_calendar(self):
data = json.loads(response.content)
self.assertEqual(2, len(data))
def format_dt_like_fullcalendar(dt):
formatted = dt.astimezone(timezone.get_current_timezone()) \
formatted = dt.astimezone(djtz.get_current_timezone()) \
.strftime('%Y-%m-%dT%H:%M:%S%z')
# FullCalendar includes ':' between hour & minute portions of the
# timzone offset. There's no way to do this directly with Python's
Expand Down Expand Up @@ -676,7 +675,7 @@ class TestEventModel(TestCase):

def setUp(self):
self.start = timeutils.round_datetime(
when=timezone.now(),
when=djtz.now(),
precision=timedelta(minutes=1),
rounding=timeutils.ROUND_DOWN)
self.end = self.start
Expand Down Expand Up @@ -726,9 +725,9 @@ def test_event_without_occurrences(self):

class TestEventRepeatsGeneratorStrangeness(TestCase):
def setUp(self):
self.start = timezone.datetime(2016,10,1, 9,0)
self.end = timezone.datetime(2016,10,1, 17)
self.repeat_end = timezone.datetime(2016,10,31, 17)
self.start = djtz.datetime(2016,10,1, 9,0)
self.end = djtz.datetime(2016,10,1, 17)
self.repeat_end = djtz.datetime(2016,10,31, 17)

self.event = G(SimpleEvent)

Expand All @@ -744,29 +743,27 @@ def test_daily_occurrences(self):
occurrences = self.event.occurrences.all()
self.assertEquals(occurrences.count(), 31)

st = timezone.localize(self.start).time()
et = timezone.localize(self.end).time()
st = djtz.localize(self.start).time()
et = djtz.localize(self.end).time()
self.assertEquals(st, time(9,0))
self.assertEquals(et, time(17,0))

for o in occurrences:
self.assertEquals(timezone.localize(o.start).time(), st)
self.assertEquals(timezone.localize(o.end).time(), et)
self.assertEquals(djtz.localize(o.start).time(), st)
self.assertEquals(djtz.localize(o.end).time(), et)

class TestEventRepeatsGeneratorModel(TestCase):

def setUp(self):
""" Create a daily recurring event with no end date """
self.start = timeutils.round_datetime(
when=timezone.now(),
when=djtz.now(),
precision=timedelta(days=1),
rounding=timeutils.ROUND_DOWN)
self.end = self.start + appsettings.DEFAULT_ENDS_DELTA

self.naive_start = make_naive(
self.start, timezone.get_current_timezone())
self.naive_end = make_naive(
self.end, timezone.get_current_timezone())
self.naive_start = coerce_naive(self.start)
self.naive_end = coerce_naive(self.end)

def test_uses_recurrencerulefield(self):
"""
Expand Down Expand Up @@ -956,7 +953,7 @@ def setUp(self):
Create an event with a daily repeat generator.
"""
self.start = timeutils.round_datetime(
when=timezone.now(),
when=djtz.now(),
precision=timedelta(days=1),
rounding=timeutils.ROUND_DOWN)
self.end = self.start + appsettings.DEFAULT_ENDS_DELTA
Expand All @@ -980,13 +977,11 @@ def test_initial_event_occurrences_automatically_created(self):
for days_hence in range(20):
start = first_occurrence.start + timedelta(days=days_hence)
self.assertTrue(
make_naive(start, timezone.get_current_timezone())
in occurrence_starts,
coerce_naive(start) in occurrence_starts,
"Missing start time %d days hence" % days_hence)
end = first_occurrence.end + timedelta(days=days_hence)
self.assertTrue(
make_naive(end, timezone.get_current_timezone())
in occurrence_ends,
coerce_naive(end) in occurrence_ends,
"Missing end time %d days hence" % days_hence)
# Confirm Event correctly returns first & last occurrences
self.assertEqual(
Expand Down Expand Up @@ -1075,12 +1070,10 @@ def test_add_arbitrary_occurrence_to_nonrepeating_event(self):
self.assertTrue(added_occurrence.is_user_modified)

def test_add_arbitrary_occurrences_to_repeating_event(self):
arbitrary_dt1 = make_naive(
self.start + timedelta(days=3, hours=-2),
timezone.get_current_timezone())
arbitrary_dt2 = make_naive(
self.start + timedelta(days=7, hours=5),
timezone.get_current_timezone())
arbitrary_dt1 = coerce_naive(
self.start + timedelta(days=3, hours=-2))
arbitrary_dt2 = coerce_naive(
self.start + timedelta(days=7, hours=5))
event = G(SimpleEvent)
generator = G(
models.EventRepeatsGenerator,
Expand Down Expand Up @@ -1143,10 +1136,10 @@ def test_cancel_arbitrary_occurrence_from_repeating_event(self):
occurrence_to_cancel_2 = event.occurrences.all()[5]
occurrence_starts, __ = get_occurrence_times_for_event(event)
self.assertTrue(
make_naive(occurrence_to_cancel_1.start, timezone.get_current_timezone())
coerce_naive(occurrence_to_cancel_1.start)
in occurrence_starts)
self.assertTrue(
make_naive(occurrence_to_cancel_2.start, timezone.get_current_timezone())
coerce_naive(occurrence_to_cancel_2.start)
in occurrence_starts)
# Cancel occurrences
event.cancel_occurrence(occurrence_to_cancel_1)
Expand Down
6 changes: 3 additions & 3 deletions icekit_events/utils/timeutils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from datetime import datetime, timedelta

from timezone import timezone
from timezone import timezone as djtz # django-timezone

ROUND_DOWN = 'ROUND_DOWN'
ROUND_NEAREST = 'ROUND_NEAREST'
Expand Down Expand Up @@ -40,7 +40,7 @@ def round_datetime(when=None, precision=60, rounding=ROUND_NEAREST):
The rounding method to use (ROUND_DOWN, ROUND_NEAREST, ROUND_UP).
"""
when = when or timezone.now()
when = when or djtz.now()
weekday = WEEKDAYS.get(precision, WEEKDAYS['MON'])
if precision in WEEKDAYS:
precision = int(timedelta(days=7).total_seconds())
Expand All @@ -49,7 +49,7 @@ def round_datetime(when=None, precision=60, rounding=ROUND_NEAREST):
# Get delta between the beginning of time and the given datetime object.
# If precision is a weekday, the beginning of time must be that same day.
when_min = when.min + timedelta(days=weekday)
if timezone.is_aware(when):
if djtz.is_aware(when):
# It doesn't seem to be possible to localise `datetime.min` without
# raising `OverflowError`, so create a timezone aware object manually.
when_min = datetime(tzinfo=when.tzinfo, *when_min.timetuple()[:3])
Expand Down

0 comments on commit 77f2cb7

Please sign in to comment.