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):
inlines = [OpenTimeInline, ]
fieldsets = (
(None, {
'fields': ('name',
('valid_start', 'valid_end'), )
# (name, (start, end))
'fields': ('name', ('valid_start', 'valid_end'))
}),
)
......
......@@ -9,13 +9,15 @@ import re
from .models import Facility
def export_data():
"""
"""
facilities = list()
# Sort the facilities by alphabetical order ignoring "the" and "a"
alphalist = sorted(Facility.objects.all(),
key=lambda r: re.sub('^(the|a) ', '', r.name, count=1,
flags=re.IGNORECASE))
key=lambda r: re.sub('^(the|a) ', '', r.name,
count=1, flags=re.IGNORECASE))
for facility in alphalist:
facility_data = {
'name': facility.name,
......@@ -26,35 +28,36 @@ def export_data():
open_times = list()
# Sort open times by their start day and time
sorted_times = sorted(facility.main_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:
open_times.append({
'start_day': time.start_day,
'start_time': time.start_time.isoformat(),
'end_day': time.end_day,
'end_time': time.end_time.isoformat()
'start_day': time.start_day,
'start_time': time.start_time.isoformat(),
'end_day': time.end_day,
'end_time': time.end_time.isoformat()
})
facility_data['main_schedule'] = {
'name': facility.main_schedule.name,
'open_times': open_times
'name': facility.main_schedule.name,
'open_times': open_times
}
special_schedules = list()
for schedule in facility.special_schedules.all():
open_times = list()
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:
open_times.append({
'start_day': time.start_day,
'start_time': time.start_time.isoformat(),
'end_day': time.end_day,
'end_time': time.end_time.isoformat()
'start_day': time.start_day,
'start_time': time.start_time.isoformat(),
'end_day': time.end_day,
'end_time': time.end_time.isoformat()
})
special_schedules.append({
'name': schedule.name,
'start': schedule.valid_start.isoformat(),
'end': schedule.valid_end.isoformat(),
'open_times': open_times
'name': schedule.name,
'start': schedule.valid_start.isoformat(),
'end': schedule.valid_end.isoformat(),
'open_times': open_times
})
facility_data['special_schedules'] = special_schedules
facilities.append(facility_data)
......
......@@ -12,6 +12,8 @@ from model_utils.models import TimeStampedModel
from autoslug import AutoSlugField
class Category(TimeStampedModel):
"""
"""
name = models.CharField(max_length=100)
class Meta:
......@@ -27,18 +29,17 @@ class Location(TimeStampedModel):
"""
Represents a specific location (unique lat, lon) that a Facility can be
found in real life.
"""
# The building that the facility is located in (on campus)
building = models.CharField(max_length=100, null=True, blank=True)
# The physical address of the facility
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)
class Facility(TimeStampedModel):
"""
Represents a specific facility location.
"""
# The name of the Facility
name = models.CharField(max_length=100)
......@@ -46,10 +47,12 @@ class Facility(TimeStampedModel):
slug = AutoSlugField(populate_from='name', unique=True)
# 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)
# 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
owners = models.ManyToManyField(User)
......@@ -57,12 +60,15 @@ class Facility(TimeStampedModel):
# The schedule that is defaulted to if no special schedule is in effect
main_schedule = models.ForeignKey('Schedule',
related_name='facility_main')
# A schedule that has a specific start and end date
special_schedules = models.ManyToManyField('Schedule',
related_name='facility_special',
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:
verbose_name = "facility"
......@@ -76,7 +82,6 @@ class Facility(TimeStampedModel):
First checks any valid special schedules and then checks the
main default schedule.
"""
today = datetime.datetime.today().date()
# Check special schedules first
......@@ -101,20 +106,23 @@ class Schedule(TimeStampedModel):
For special (temporary) schedules, start and end dates for
when this schedule will be valid can also be set.
"""
name = models.CharField(max_length=100)
# inclusive:
# (inclusive)
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,
help_text='Last day that this schedule is in effect')
help_text="""Last day that this schedule is
in effect""")
class Meta:
ordering = ['name']
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):
if time.isOpenNow():
return True
......@@ -125,8 +133,9 @@ class Schedule(TimeStampedModel):
class OpenTime(TimeStampedModel):
"""Represents a period time when a Facility is open"""
"""
Represents a period time when a Facility is open.
"""
MONDAY = 0
TUESDAY = 1
WEDNESDAY = 2
......@@ -146,13 +155,16 @@ class OpenTime(TimeStampedModel):
)
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()
end_day = models.IntegerField(default=0, choices=DAY_CHOICES)
end_time = models.TimeField()
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()
if self.start_day <= self.end_day:
if self.start_day == today.weekday():
......@@ -178,7 +190,9 @@ class OpenTime(TimeStampedModel):
def __str__(self):
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday',
'Saturday', 'Sunday']
'Saturday', 'Sunday']
return '%s %s to %s %s' % (weekdays[self.start_day],
self.start_time.strftime("%H:%M:%S"), weekdays[self.end_day],
self.end_time.strftime("%H:%M:%S"))
self.start_time.strftime("%H:%M:%S"),
# to
weekdays[self.end_day],
self.end_time.strftime("%H:%M:%S"))
......@@ -9,23 +9,32 @@ from .models import Category, Facility, Schedule, OpenTime
from rest_framework import serializers
class CategorySerializer(serializers.ModelSerializer):
"""
"""
class Meta:
model = Category
fields = '__all__'
class OpenTimeSerializer(serializers.ModelSerializer):
"""
"""
class Meta:
model = OpenTime
fields = '__all__'
class ScheduleSerializer(serializers.ModelSerializer):
"""
"""
open_times = OpenTimeSerializer(many=True, read_only=True)
class Meta:
model = Schedule
fields = ('id', 'open_times', 'modified', 'name', 'valid_start',
'valid_end')
class FacilitySerializer(serializers.HyperlinkedModelSerializer):
"""
"""
category = CategorySerializer(many=False, read_only=True)
main_schedule = ScheduleSerializer(many=False, read_only=True)
special_schedules = ScheduleSerializer(many=True, read_only=True)
......
......@@ -12,7 +12,7 @@ from .views import CategoryViewSet, FacilityViewSet, ScheduleViewSet
# Other Imports
from rest_framework.routers import DefaultRouter
# Instiantiate our DefaultRouter
# Instantiate our DefaultRouter
ROUTER = DefaultRouter()
# Register views to the API router
......
......@@ -2,38 +2,30 @@
from __future__ import (absolute_import, division, print_function,
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
from .models import Facility, OpenTime, Category, Schedule
from .api import export_data
from .serializers import CategorySerializer, FacilitySerializer, ScheduleSerializer, OpenTimeSerializer
from .serializers import (CategorySerializer, FacilitySerializer,
ScheduleSerializer, OpenTimeSerializer)
# Other Imports
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import viewsets
# Rest Framework Class Views
class CategoryViewSet(viewsets.ReadOnlyModelViewSet):
"""
"""
queryset = Category.objects.all()
serializer_class = CategorySerializer
class FacilityViewSet(viewsets.ReadOnlyModelViewSet):
"""
"""
queryset = Facility.objects.all()
serializer_class = FacilitySerializer
def get_queryset(self):
"""
"""
queryset = Facility.objects.all()
open_now = self.request.query_params.get('open', None)
if open_now is not None:
......@@ -48,15 +40,13 @@ class FacilityViewSet(viewsets.ReadOnlyModelViewSet):
return queryset
class ScheduleViewSet(viewsets.ModelViewSet):
"""
"""
queryset = Schedule.objects.all()
serializer_class = ScheduleSerializer
class OpenTimeViewSet(viewsets.ModelViewSet):
"""
"""
queryset = OpenTime.objects.all()
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