|
133
|
1 |
''' |
|
|
2 |
field serializing and deserializing metacategorization protocols |
|
|
3 |
''' |
|
142
|
4 |
import json |
|
133
|
5 |
import logging |
|
|
6 |
|
|
|
7 |
from rest_framework import serializers |
|
|
8 |
|
|
142
|
9 |
from notes import constants, settings |
|
|
10 |
from protocols.models import Protocol, ProtocolRevision |
|
|
11 |
from protocols.serializers import ProtocolRevisionSerializer |
|
|
12 |
|
|
133
|
13 |
logger = logging.getLogger(__name__) |
|
|
14 |
|
|
|
15 |
class ProtocolField(serializers.Field): |
|
|
16 |
|
|
142
|
17 |
default_error_messages = { |
|
|
18 |
'incorrect_format_str': 'Incorrect format. Expected `'+constants.PROTOCOL_URN_PREFIX+'<ext_id>.<version>`.', |
|
|
19 |
'protocol_unknown': 'Incorrect protocol, protocol {ext_id}, version {version} does not exists.', |
|
|
20 |
'incorrect_format': 'Incorrect format. Expected `'+constants.PROTOCOL_URN_PREFIX+'<ext_id>.<version>` or dict.' |
|
|
21 |
} |
|
|
22 |
|
|
|
23 |
def __init__(self, *args, **kwargs): |
|
|
24 |
logger.debug("ProtocolField.__init__ %r || %r", args, kwargs) |
|
|
25 |
super().__init__(*args, **kwargs) |
|
133
|
26 |
|
|
142
|
27 |
# def get_attribute(self, *args, **kwargs): |
|
|
28 |
# logger.debug("ProtocolField.get_attribute %r || %r", args, kwargs) |
|
|
29 |
# logger.debug("ProtocolField.get_attribute source %r", self.source) |
|
|
30 |
# # We pass the object instance onto `to_representation`, |
|
|
31 |
# # not just the field attribute. |
|
|
32 |
# return kwargs.get('obj') |
|
|
33 |
|
|
|
34 |
def to_representation(self, value): |
|
|
35 |
if isinstance(value, str) and value.startswith(constants.PROTOCOL_URN_PREFIX) : |
|
|
36 |
protocol_id, protocol_version = value[len(constants.PROTOCOL_URN_PREFIX):].split('.') |
|
|
37 |
# TODO: treat error case, i.e. protocol is not found |
|
|
38 |
protocol_revision = ProtocolRevision.objects.get(protocol__ext_id=protocol_id, version=protocol_version) |
|
|
39 |
serializer = ProtocolRevisionSerializer(protocol_revision) |
|
|
40 |
return serializer.data |
|
|
41 |
elif isinstance(value, str): |
|
|
42 |
logger.debug("ProtocolField.to_representation value %r" % value) |
|
|
43 |
return json.loads(value) |
|
|
44 |
else: |
|
|
45 |
return value |
|
|
46 |
|
|
133
|
47 |
|
|
|
48 |
def to_internal_value(self, data): |
|
|
49 |
|
|
142
|
50 |
if isinstance(data, str) and data.startswith(constants.PROTOCOL_URN_PREFIX): |
|
|
51 |
try: |
|
|
52 |
ext_id, version = data[len(constants.PROTOCOL_URN_PREFIX):].split('.') |
|
|
53 |
except ValueError: |
|
|
54 |
self.fail('incorrect_format_str') |
|
|
55 |
if not ProtocolRevision.objects.filter(protocol__ext_id=ext_id, version=version).exists(): |
|
|
56 |
self.fail('protocol_unknown', ext_id=ext_id, version=version) |
|
|
57 |
else: |
|
|
58 |
return data |
|
|
59 |
elif isinstance(data, dict): |
|
|
60 |
return data |
|
|
61 |
else: |
|
|
62 |
self.fail('incorrect_format') |