Verified Commit 4b573430 authored by David Haynes's avatar David Haynes 🙆
Browse files

Formatting, readability, comments, etc.

- some things that were bugging me that I think can be agreed
upon as overall good
parent 725c42de
Pipeline #1362 passed with stage
in 1 minute and 22 seconds
...@@ -36,8 +36,8 @@ class ScheduleAdmin(admin.ModelAdmin): ...@@ -36,8 +36,8 @@ class ScheduleAdmin(admin.ModelAdmin):
inlines = [OpenTimeInline, ] inlines = [OpenTimeInline, ]
fieldsets = ( fieldsets = (
(None, { (None, {
'fields': ('name', # (name, (start, end))
('valid_start', 'valid_end'), ) 'fields': ('name', ('valid_start', 'valid_end'))
}), }),
) )
......
...@@ -9,12 +9,14 @@ import re ...@@ -9,12 +9,14 @@ import re
from .models import Facility from .models import Facility
def export_data(): def export_data():
"""
"""
facilities = list() facilities = list()
# Sort the facilities by alphabetical order ignoring "the" and "a" # Sort the facilities by alphabetical order ignoring "the" and "a"
alphalist = sorted(Facility.objects.all(), alphalist = sorted(Facility.objects.all(),
key=lambda r: re.sub('^(the|a) ', '', r.name, count=1, key=lambda r: re.sub('^(the|a) ', '', r.name,
flags=re.IGNORECASE)) count=1, flags=re.IGNORECASE))
for facility in alphalist: for facility in alphalist:
facility_data = { facility_data = {
...@@ -42,7 +44,8 @@ def export_data(): ...@@ -42,7 +44,8 @@ def export_data():
for schedule in facility.special_schedules.all(): for schedule in facility.special_schedules.all():
open_times = list() open_times = list()
sorted_times = sorted(schedule.open_times.all(), sorted_times = sorted(schedule.open_times.all(),
key=lambda t: (t.start_day, t.start_time, t.end_time)) key=lambda t: (
t.start_day, t.start_time, t.end_time))
for time in sorted_times: for time in sorted_times:
open_times.append({ open_times.append({
'start_day': time.start_day, 'start_day': time.start_day,
......
...@@ -12,6 +12,8 @@ from model_utils.models import TimeStampedModel ...@@ -12,6 +12,8 @@ from model_utils.models import TimeStampedModel
from autoslug import AutoSlugField from autoslug import AutoSlugField
class Category(TimeStampedModel): class Category(TimeStampedModel):
"""
"""
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
class Meta: class Meta:
...@@ -27,18 +29,17 @@ class Location(TimeStampedModel): ...@@ -27,18 +29,17 @@ class Location(TimeStampedModel):
""" """
Represents a specific location (unique lat, lon) that a Facility can be Represents a specific location (unique lat, lon) that a Facility can be
found in real life. found in real life.
""" """
# The building that the facility is located in (on campus) # The building that the facility is located in (on campus)
building = models.CharField(max_length=100, null=True, blank=True) building = models.CharField(max_length=100, null=True, blank=True)
# The physical address of the facility # The physical address of the facility
address = models.CharField(max_length=100, null=True, blank=True) address = models.CharField(max_length=100, null=True, blank=True)
# Boolean for whether or not the location is "on campus" or not
on_campus = models.BooleanField(default=True) on_campus = models.BooleanField(default=True)
class Facility(TimeStampedModel): class Facility(TimeStampedModel):
""" """
Represents a specific facility location. Represents a specific facility location.
""" """
# The name of the Facility # The name of the Facility
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
...@@ -46,10 +47,12 @@ class Facility(TimeStampedModel): ...@@ -46,10 +47,12 @@ class Facility(TimeStampedModel):
slug = AutoSlugField(populate_from='name', unique=True) slug = AutoSlugField(populate_from='name', unique=True)
# The category that this facility falls under # The category that this facility falls under
facility_category = models.ForeignKey('Category', related_name="facilities", facility_category = models.ForeignKey('Category',
related_name="facilities",
null=True, blank=True) null=True, blank=True)
# The location object that relates to this facility # The location object that relates to this facility
facility_location = models.ForeignKey('Location', related_name="facilities") facility_location = models.ForeignKey('Location',
related_name="facilities")
# The User(s) that claim ownership over this facility # The User(s) that claim ownership over this facility
owners = models.ManyToManyField(User) owners = models.ManyToManyField(User)
...@@ -57,12 +60,15 @@ class Facility(TimeStampedModel): ...@@ -57,12 +60,15 @@ class Facility(TimeStampedModel):
# The schedule that is defaulted to if no special schedule is in effect # The schedule that is defaulted to if no special schedule is in effect
main_schedule = models.ForeignKey('Schedule', main_schedule = models.ForeignKey('Schedule',
related_name='facility_main') related_name='facility_main')
# A schedule that has a specific start and end date # A schedule that has a specific start and end date
special_schedules = models.ManyToManyField('Schedule', special_schedules = models.ManyToManyField('Schedule',
related_name='facility_special', related_name='facility_special',
blank=True, blank=True,
help_text='This schedule will come into effect only for its specified duration.') help_text="""This schedule will
come into effect
only for its
specified duration.
""")
class Meta: class Meta:
verbose_name = "facility" verbose_name = "facility"
...@@ -76,7 +82,6 @@ class Facility(TimeStampedModel): ...@@ -76,7 +82,6 @@ class Facility(TimeStampedModel):
First checks any valid special schedules and then checks the First checks any valid special schedules and then checks the
main default schedule. main default schedule.
""" """
today = datetime.datetime.today().date() today = datetime.datetime.today().date()
# Check special schedules first # Check special schedules first
...@@ -101,20 +106,23 @@ class Schedule(TimeStampedModel): ...@@ -101,20 +106,23 @@ class Schedule(TimeStampedModel):
For special (temporary) schedules, start and end dates for For special (temporary) schedules, start and end dates for
when this schedule will be valid can also be set. when this schedule will be valid can also be set.
""" """
name = models.CharField(max_length=100) name = models.CharField(max_length=100)
# inclusive: # (inclusive)
valid_start = models.DateField('Start Date', null=True, blank=True, valid_start = models.DateField('Start Date', null=True, blank=True,
help_text='Date that this schedule goes into effect') help_text="""Date that this schedule goes
into effect""")
valid_end = models.DateField('End Date', null=True, blank=True, valid_end = models.DateField('End Date', null=True, blank=True,
help_text='Last day that this schedule is in effect') help_text="""Last day that this schedule is
in effect""")
class Meta: class Meta:
ordering = ['name'] ordering = ['name']
def isOpenNow(self): def isOpenNow(self):
"""Return true if this schedule is open right now.""" """
Return true if this schedule is open right now.
"""
for time in OpenTime.objects.filter(schedule=self): for time in OpenTime.objects.filter(schedule=self):
if time.isOpenNow(): if time.isOpenNow():
return True return True
...@@ -125,8 +133,9 @@ class Schedule(TimeStampedModel): ...@@ -125,8 +133,9 @@ class Schedule(TimeStampedModel):
class OpenTime(TimeStampedModel): class OpenTime(TimeStampedModel):
"""Represents a period time when a Facility is open""" """
Represents a period time when a Facility is open.
"""
MONDAY = 0 MONDAY = 0
TUESDAY = 1 TUESDAY = 1
WEDNESDAY = 2 WEDNESDAY = 2
...@@ -146,13 +155,16 @@ class OpenTime(TimeStampedModel): ...@@ -146,13 +155,16 @@ class OpenTime(TimeStampedModel):
) )
schedule = models.ForeignKey('Schedule', related_name='open_times') schedule = models.ForeignKey('Schedule', related_name='open_times')
start_day = models.IntegerField(default=0, choices=DAY_CHOICES) # 0-6, Monday == 0 # 0-6, Monday == 0
start_day = models.IntegerField(default=0, choices=DAY_CHOICES)
start_time = models.TimeField() start_time = models.TimeField()
end_day = models.IntegerField(default=0, choices=DAY_CHOICES) end_day = models.IntegerField(default=0, choices=DAY_CHOICES)
end_time = models.TimeField() end_time = models.TimeField()
def isOpenNow(self): def isOpenNow(self):
"""Return true if the current time is this OpenTime's range""" """
Return true if the current time is this OpenTime's range
"""
today = datetime.datetime.today() today = datetime.datetime.today()
if self.start_day <= self.end_day: if self.start_day <= self.end_day:
if self.start_day == today.weekday(): if self.start_day == today.weekday():
...@@ -180,5 +192,7 @@ class OpenTime(TimeStampedModel): ...@@ -180,5 +192,7 @@ class OpenTime(TimeStampedModel):
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday', 'Sunday'] 'Saturday', 'Sunday']
return '%s %s to %s %s' % (weekdays[self.start_day], return '%s %s to %s %s' % (weekdays[self.start_day],
self.start_time.strftime("%H:%M:%S"), weekdays[self.end_day], self.start_time.strftime("%H:%M:%S"),
# to
weekdays[self.end_day],
self.end_time.strftime("%H:%M:%S")) self.end_time.strftime("%H:%M:%S"))
...@@ -9,23 +9,32 @@ from .models import Category, Facility, Schedule, OpenTime ...@@ -9,23 +9,32 @@ from .models import Category, Facility, Schedule, OpenTime
from rest_framework import serializers from rest_framework import serializers
class CategorySerializer(serializers.ModelSerializer): class CategorySerializer(serializers.ModelSerializer):
"""
"""
class Meta: class Meta:
model = Category model = Category
fields = '__all__' fields = '__all__'
class OpenTimeSerializer(serializers.ModelSerializer): class OpenTimeSerializer(serializers.ModelSerializer):
"""
"""
class Meta: class Meta:
model = OpenTime model = OpenTime
fields = '__all__' fields = '__all__'
class ScheduleSerializer(serializers.ModelSerializer): class ScheduleSerializer(serializers.ModelSerializer):
"""
"""
open_times = OpenTimeSerializer(many=True, read_only=True) open_times = OpenTimeSerializer(many=True, read_only=True)
class Meta: class Meta:
model = Schedule model = Schedule
fields = ('id', 'open_times', 'modified', 'name', 'valid_start', fields = ('id', 'open_times', 'modified', 'name', 'valid_start',
'valid_end') 'valid_end')
class FacilitySerializer(serializers.HyperlinkedModelSerializer): class FacilitySerializer(serializers.HyperlinkedModelSerializer):
"""
"""
category = CategorySerializer(many=False, read_only=True) category = CategorySerializer(many=False, read_only=True)
main_schedule = ScheduleSerializer(many=False, read_only=True) main_schedule = ScheduleSerializer(many=False, read_only=True)
special_schedules = ScheduleSerializer(many=True, read_only=True) special_schedules = ScheduleSerializer(many=True, read_only=True)
......
...@@ -12,7 +12,7 @@ from .views import CategoryViewSet, FacilityViewSet, ScheduleViewSet ...@@ -12,7 +12,7 @@ from .views import CategoryViewSet, FacilityViewSet, ScheduleViewSet
# Other Imports # Other Imports
from rest_framework.routers import DefaultRouter from rest_framework.routers import DefaultRouter
# Instiantiate our DefaultRouter # Instantiate our DefaultRouter
ROUTER = DefaultRouter() ROUTER = DefaultRouter()
# Register views to the API router # Register views to the API router
......
...@@ -2,38 +2,30 @@ ...@@ -2,38 +2,30 @@
from __future__ import (absolute_import, division, print_function, from __future__ import (absolute_import, division, print_function,
unicode_literals) unicode_literals)
# Python stdlib Imports
import hashlib
import json
# Django Imports
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.views.decorators.http import condition
from django.views.generic import ListView, DetailView
from model_utils.models import TimeStampedModel
# App Imports # App Imports
from .models import Facility, OpenTime, Category, Schedule from .models import Facility, OpenTime, Category, Schedule
from .api import export_data from .serializers import (CategorySerializer, FacilitySerializer,
from .serializers import CategorySerializer, FacilitySerializer, ScheduleSerializer, OpenTimeSerializer ScheduleSerializer, OpenTimeSerializer)
# Other Imports # Other Imports
from rest_framework import viewsets, status from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.decorators import api_view
# Rest Framework Class Views # Rest Framework Class Views
class CategoryViewSet(viewsets.ReadOnlyModelViewSet): class CategoryViewSet(viewsets.ReadOnlyModelViewSet):
"""
"""
queryset = Category.objects.all() queryset = Category.objects.all()
serializer_class = CategorySerializer serializer_class = CategorySerializer
class FacilityViewSet(viewsets.ReadOnlyModelViewSet): class FacilityViewSet(viewsets.ReadOnlyModelViewSet):
"""
"""
queryset = Facility.objects.all() queryset = Facility.objects.all()
serializer_class = FacilitySerializer serializer_class = FacilitySerializer
def get_queryset(self): def get_queryset(self):
"""
"""
queryset = Facility.objects.all() queryset = Facility.objects.all()
open_now = self.request.query_params.get('open', None) open_now = self.request.query_params.get('open', None)
if open_now is not None: if open_now is not None:
...@@ -48,15 +40,13 @@ class FacilityViewSet(viewsets.ReadOnlyModelViewSet): ...@@ -48,15 +40,13 @@ class FacilityViewSet(viewsets.ReadOnlyModelViewSet):
return queryset return queryset
class ScheduleViewSet(viewsets.ModelViewSet): class ScheduleViewSet(viewsets.ModelViewSet):
"""
"""
queryset = Schedule.objects.all() queryset = Schedule.objects.all()
serializer_class = ScheduleSerializer serializer_class = ScheduleSerializer
class OpenTimeViewSet(viewsets.ModelViewSet): class OpenTimeViewSet(viewsets.ModelViewSet):
"""
"""
queryset = OpenTime.objects.all() queryset = OpenTime.objects.all()
serializer_class = OpenTimeSerializer serializer_class = OpenTimeSerializer
def gen_etag(request):
return hashlib.sha1(str(OpenTime.objects.all())).hexdigest()
def gen_last_modified(request):
return TimeStampedModel.objects.all().order_by('-last_modified')[0].last_modified
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment