-
Notifications
You must be signed in to change notification settings - Fork 0
/
views.py
181 lines (137 loc) · 6.05 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
from django.http import Http404
from django.utils import translation
from functools import cached_property
from rest_framework.exceptions import APIException, ValidationError, PermissionDenied, NotFound
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView, CreateAPIView
from .exceptions import ConfigError
from .parsers import PlainTextParser
from .serializers import ParticipantSerializer
from experiments.models import DataPoint, Experiment, ParticipantSession
class ResultCodes:
OK = "OK"
ERR_NO_ID = "ERR_NO_ID"
ERR_NO_DATA = "ERR_NO_DATA"
ERR_UNKNOWN_ID = "ERR_UNKNOWN_ID"
ERR_NOT_OPEN = "ERR_NOT_OPEN"
ERR_GROUP_ASSIGN_FAIL = "ERR_GROUP_ASSIGN_FAIL"
ERR_NO_SESSION = "ERR_NO_SESSION"
class BaseExperimentApiView(GenericAPIView):
lookup_field = 'access_id'
lookup_url_kwarg = 'access_key'
queryset = Experiment.objects.all()
def dispatch(self, *args, **kwargs):
# API responses should always use English messages
with translation.override('en'):
return super().dispatch(*args, **kwargs)
def get_object(self):
try:
return super().get_object()
except Http404:
raise NotFound(code=ResultCodes.ERR_UNKNOWN_ID,
detail='No experiment using that id was found')
@cached_property
def experiment(self):
return self.get_object()
class MetadataView(BaseExperimentApiView):
# List of all variables that are retrievable
fields = ('state', )
def get(self, request, access_key, field=None):
if field in self.fields:
return Response(self.get_value(self.experiment, field))
return Response({field: self.get_value(self.experiment, field) for field in self.fields})
@staticmethod
def get_value(experiment: Experiment, field):
methods = dir(experiment)
try:
method = "get_{}_display".format(field)
# If this field has an explicit display method, use that
if method in methods:
return getattr(experiment, method)()
else:
# Otherwise, just get the value
return getattr(experiment, field)
except AttributeError:
return None
class BaseUploadView(BaseExperimentApiView):
"""Base view for uploading data into an experiment.
It only accepts plain text content, as otherwise the Django Rest
Framework tries to force the data into a Python format. Not only is this
fault intolerant, we want to store the data as raw as possible.
Raw data doesn't lose resolution, and allows for more flexibility later on.
This view also checks several things:
- A valid access key should be used
- The experiment should be approved
- The experiment should have the 'OPEN' state
If any of these conditions are not met, an error should be returned.
"""
parser_classes = [PlainTextParser]
def _validate_request(self, payload):
# Error if no data was sent
if not payload:
raise APIException(code=ResultCodes.ERR_NO_DATA, detail='No data was provided')
# The experiment should be approved and open.
if not self.experiment.is_open():
raise PermissionDenied(code=ResultCodes.ERR_NOT_OPEN,
detail='The experiment is not open to new uploads')
def _save_data_point(self, payload, session: ParticipantSession):
dp = DataPoint()
dp.experiment = self.experiment
dp.data = payload
dp.session = session
dp.save()
return dp
class UploadView(BaseUploadView):
def post(self, request, access_key):
payload = request.data
self._validate_request(payload)
if self.experiment.uses_groups():
# If the experiment is configured to use target groups,
# then session ids are mandatory
raise ConfigError(code=ResultCodes.ERR_NO_SESSION,
detail='Missing participant session id')
session = ParticipantSession.objects.create(experiment=self.experiment)
session.complete()
dp = self._save_data_point(payload, session)
return Response({
'result': ResultCodes.OK,
'message': 'Upload successful'
})
class SessionUploadView(BaseUploadView):
def post(self, request, access_key, participant_id):
payload = request.data
self._validate_request(payload)
if not self.experiment.uses_groups():
raise ValidationError(detail='Experiment is not using session ids')
try:
participant = self.experiment.participantsession_set\
.get(uuid=participant_id)
except ParticipantSession.DoesNotExist:
raise PermissionDenied(code=ResultCodes.ERR_NO_SESSION,
detail='Bad participant session id')
# Create the new datapoint
dp = self._save_data_point(payload, participant)
participant.complete()
# Return that everything went OK
return Response({
"result": ResultCodes.OK,
"message": "Upload successful"
})
class ParticipantView(BaseExperimentApiView, CreateAPIView):
serializer_class = ParticipantSerializer
def create(self, *args, **kwargs):
"""creates a new participant session"""
if not self.experiment.is_open():
raise PermissionDenied(code=ResultCodes.ERR_NOT_OPEN,
detail="The experiment is not open to new uploads")
group = self.experiment.get_next_group()
if not group:
raise ConfigError(code=ResultCodes.ERR_GROUP_ASSIGN_FAIL,
detail='Could not assign participant to any group')
participant = ParticipantSession.objects.create(
experiment=self.experiment,
state=ParticipantSession.STARTED,
group=group
)
serialized = self.serializer_class(participant)
return Response(serialized.data)