src/notes/api/fields/category.py
changeset 142 56850f5c73f6
parent 139 d3738ac909d8
equal deleted inserted replaced
141:cd5e8fb64b74 142:56850f5c73f6
     1 '''
     1 '''
     2 field serializing and deserializing metacategorization protocols
     2 field serializing and deserializing metacategorization protocols
     3 '''
     3 '''
       
     4 import json
     4 import logging
     5 import logging
     5 
     6 
     6 from notes import settings
       
     7 from rest_framework import serializers
     7 from rest_framework import serializers
       
     8 
       
     9 from notes import constants, settings
       
    10 from protocols.models import Protocol, ProtocolRevision
       
    11 from protocols.serializers import ProtocolRevisionSerializer
     8 
    12 
     9 logger = logging.getLogger(__name__)
    13 logger = logging.getLogger(__name__)
    10 
    14 
    11 class ProtocolField(serializers.Field):
    15 class ProtocolField(serializers.Field):
    12 
    16 
    13     def get_attribute(self, obj):
    17     default_error_messages = {
    14         logger.debug("ProtocolField.get_attribute %r", obj)
    18         'incorrect_format_str': 'Incorrect format. Expected `'+constants.PROTOCOL_URN_PREFIX+'<ext_id>.<version>`.',
    15         # We pass the object instance onto `to_representation`,
    19         'protocol_unknown': 'Incorrect protocol, protocol {ext_id}, version {version} does not exists.',
    16         # not just the field attribute.
    20         'incorrect_format': 'Incorrect format. Expected `'+constants.PROTOCOL_URN_PREFIX+'<ext_id>.<version>` or dict.'
    17         return obj
    21     }
    18 
    22 
    19     def to_representation(self, obj):
    23     def __init__(self, *args, **kwargs):
    20         logger.debug("ProtocolField.to_representation %r", obj)
    24         logger.debug("ProtocolField.__init__ %r || %r", args, kwargs)
    21         return settings.NOTES_SETTINGS['PROTOCOL']
    25         super().__init__(*args, **kwargs)
       
    26 
       
    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 
    22 
    47 
    23     def to_internal_value(self, data):
    48     def to_internal_value(self, data):
    24         logger.debug("ProtocolField.to_internal_value %r", data)
       
    25         return "base protocol"
       
    26 
    49 
       
    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')