""" JSON serializers for database models.
Classes here parses python objects into JSON formats to be transmitted with HTTP requests to the Pi
or to client Javascript code.
Jin Cheng, 02/12/16
"""
from django.utils import timezone
from rest_framework import serializers
from server_side.controls.models import Calorimeter, Run, DataPoint
[docs]class CalorimeterSerializer(serializers.ModelSerializer):
"""JSON representation of calorimetry settings."""
is_active = serializers.SerializerMethodField('is_calorimeter_active')
has_active_runs = serializers.SerializerMethodField('check_active_runs')
def __init__(self, *args, **kwargs):
super(CalorimeterSerializer, self).__init__(*args, **kwargs)
self.from_device = False
if 'from_device' in kwargs:
if kwargs['from_device']:
self.from_device = True
[docs] def is_calorimeter_active(self, instance):
time_delta = instance.last_comm_time - timezone.now()
return abs(time_delta.total_seconds()) < 60
[docs] def check_active_runs(self, instance):
kwargs = {'calorimeter': instance, 'is_finished': False}
if Run.objects.filter(**kwargs).exists():
active_run = Run.objects.filter(**kwargs).order_by('-start_time')[0]
return RunSerializer(active_run).data
return False
[docs] def update(self, instance, validated_data):
instance.last_comm_time = timezone.now()
super(CalorimeterSerializer, self).update(instance, validated_data)
return instance
[docs]class DataPointSerializer(serializers.ModelSerializer):
"""JSON representation of measurements made at a certain point in time."""
measured_at = serializers.DateTimeField(input_formats=['iso-8601'])
run = serializers.PrimaryKeyRelatedField(queryset=Run.objects.all(), validators=[])
[docs]class RunSerializer(serializers.ModelSerializer):
"""JSON representation of a calorimetry job."""
calorimeter = serializers.PrimaryKeyRelatedField(queryset=Calorimeter.objects.all(), validators=[])
data_point_count = serializers.SerializerMethodField('count_data_points')
[docs] def count_data_points(self, instance):
return instance.datapoint_set.count()