class VipRequestPortV3Serializer(DynamicFieldsModelSerializer):
    id = serializers.Field()

    options = serializers.SerializerMethodField('get_options')
    pools = serializers.SerializerMethodField('get_pools')

    def get_pools(self, obj):
        return self.extends_serializer(obj, 'pools')

    def get_options(self, obj):
        options = obj.options
        opt = {'l4_protocol': None, 'l7_protocol': None}
        for option in options:
            if option.optionvip.tipo_opcao == 'l4_protocol':
                opt['l4_protocol'] = option
            elif option.optionvip.tipo_opcao == 'l7_protocol':
                opt['l7_protocol'] = option

        return self.extends_serializer(opt, 'options')

    class Meta:
        VipRequestPort = get_model('api_vip_request', 'VipRequestPort')
        model = VipRequestPort
        fields = (
            'id',
            'port',
            'options',
            'pools',
            'identifier',
        )

        default_fields = (
            'id',
            'port',
            'options',
            'pools',
        )

    def get_serializers(self):

        envvip_slz = get_app('api_environment_vip', module_label='serializers')

        if not self.mapping:
            self.mapping = {
                'pools': {
                    'serializer': VipRequestPortPoolV3Serializer,
                    'kwargs': {
                        'many': True
                    },
                    'obj': 'pools',
                },
                'pools__details': {
                    'serializer': VipRequestPortPoolV3Serializer,
                    'kwargs': {
                        'many': True,
                        'kind': 'details'
                    },
                    'obj': 'pools'
                },
                'options': {
                    'keys': (
                        'l4_protocol',
                        'l7_protocol',
                    ),
                    'kwargs': {},
                    'obj': 'optionvip_id'
                },
                'options__details': {
                    'keys': (
                        'l4_protocol',
                        'l7_protocol',
                    ),
                    'serializer': envvip_slz.OptionVipV3Serializer,
                    'kwargs': {
                        'kind': 'details'
                    },
                    'obj': 'optionvip',
                },
            }
        return self.mapping
Exemple #2
0
class CallrequestSerializer(serializers.HyperlinkedModelSerializer):
    """
    **Create**:

        CURL Usage::

            curl -u username:password --dump-header - -H "Content-Type:application/json" -X POST --data '{"request_uuid": "2342jtdsf-00123", "call_time": "2011-10-20 12:21:22", "phone_number": "8792749823", "content_type":"/rest-api/content_type/49/", "object_id":1, "timeout": "30000", "callerid": "650784355", "call_type": "1"}' http://localhost:8000/rest-api/callrequest/

        Response::

            HTTP/1.0 201 CREATED
            Date: Fri, 23 Sep 2011 06:08:34 GMT
            Server: WSGIServer/0.1 Python/2.7.1+
            Vary: Accept-Language, Cookie
            Content-Type: text/html; charset=utf-8
            Location: http://localhost:8000/api/app/callrequest/1/
            Content-Language: en-us


    **Read**:

        CURL Usage::

            curl -u username:password -H 'Accept: application/json' http://localhost:8000/rest-api/callrequest/

            curl -u username:password -H 'Accept: application/json' http://localhost:8000/rest-api/callrequest/%callreq_id%/

        Response::

            {
               "meta":{
                  "limit":20,
                  "next":null,
                  "offset":0,
                  "previous":null,
                  "total_count":1
               },
               "objects":[
                  {
                     "call_time":"2011-10-20T12:21:22",
                     "call_type":1,
                     "callerid":"650784355",
                     "created_date":"2011-10-14T07:33:41",
                     "extra_data":"",
                     "extra_dial_string":"",
                     "hangup_cause":"",
                     "id":"1",
                     "last_attempt_time":null,
                     "num_attempt":0,
                     "phone_number":"8792749823",
                     "request_uuid":"2342jtdsf-00123",
                     "resource_uri":"/api/v1/callrequest/1/",
                     "result":"",
                     "status":1,
                     "timelimit":3600,
                     "timeout":30000,
                     "updated_date":"2011-10-14T07:33:41",
                     "user":{
                        "first_name":"",
                        "id":"1",
                        "last_login":"******",
                        "last_name":"",
                        "resource_uri":"/api/v1/user/1/",
                        "username":"******"
                     },
                  }
               ]
            }

    **Update**:

        CURL Usage::

            curl -u username:password --dump-header - -H "Content-Type: application/json" -X PUT --data '{"content_type":"/rest-api/content_type/49/", "object_id":1, "status": "5"}' http://localhost:8000/rest-api/callrequest/%callrequest_id%/

        Response::

            HTTP/1.0 204 NO CONTENT
            Date: Fri, 23 Sep 2011 06:46:12 GMT
            Server: WSGIServer/0.1 Python/2.7.1+
            Vary: Accept-Language, Cookie
            Content-Length: 0
            Content-Type: text/html; charset=utf-8
            Content-Language: en-us

    """
    user = serializers.Field(source='user')

    class Meta:
        model = Callrequest

    def get_fields(self, *args, **kwargs):
        """filter content_type field"""
        fields = super(CallrequestSerializer, self).get_fields(*args, **kwargs)
        request = self.context['request']

        if request.method != 'GET':
            fields[
                'aleg_gateway'].queryset = request.user.userprofile.userprofile_gateway.all(
                )
            if self.object and self.object:
                fields['content_type'].queryset = ContentType.objects.filter(
                    model__in=["survey"])
            else:
                fields['content_type'].queryset = ContentType.objects.filter(
                    model__in=["survey_template"])

        return fields
Exemple #3
0
class RelativeUrlPaginationSerializer(BasePaginationSerializer):
    count = serializers.Field(source='paginator.count')
    next = RelativeNextPageField('*')
    previous = RelativePreviousPageField('*')
Exemple #4
0
class PaginationMetadataSerializer(serializers.Serializer):
    length = serializers.Field(source='paginator.count')
    next = pagination.NextPageField(source='*')
    previous = pagination.PreviousPageField(source='*')
    page = serializers.Field(source='number')
    num_pages = serializers.Field(source='paginator.num_pages')
Exemple #5
0
class CustomPaginationSerializer(pagination.BasePaginationSerializer):
    links = LinksSerializer(source='*')  # Takes the page object as the source
    total_results = serializers.Field(source='paginator.count')

    results_field = 'objects'
class CustomPaginationSerializer(pagination.BasePaginationSerializer):
    next = pagination.NextPageField(source='*')
    prev = pagination.PreviousPageField(source='*')
    total_page = serializers.Field(source="paginator.num_pages")
    total_results = serializers.Field(source='paginator.count')
Exemple #7
0
class ClientListSerializer(serializers.ModelSerializer):
    full_name = serializers.Field(source="get_full_name")
    class Meta:
        model = User
        fields = ('id', 'email', 'full_name', 'img')
class QueueSerializer(serializers.HyperlinkedModelSerializer):
    """
    **Create**:

        CURL Usage::

            curl -u username:password --dump-header - -H "Content-Type:application/json" -X POST --data '{"name": "queue name"}' http://localhost:8000/rest-api/queue/

        Response::

            HTTP/1.0 201 CREATED
            Date: Fri, 14 Jun 2013 09:52:27 GMT
            Server: WSGIServer/0.1 Python/2.7.3
            Vary: Accept, Accept-Language, Cookie
            Content-Type: application/json; charset=utf-8
            Content-Language: en-us
            Location: http://localhost:8000/rest-api/queue/1/
            Allow: GET, POST, HEAD, OPTIONS

    **Read**:

        CURL Usage::

            curl -u username:password -H 'Accept: application/json' http://localhost:8000/rest-api/queue/

        Response::

            {
                "count": 1,
                "next": null,
                "previous": null,
                "results": [
                    {
                        "manager": "manager",
                        "url": "http://127.0.0.1:8000/rest-api/queue/1/",
                        "name": "Sample queue",
                        "strategy": 5,
                        "moh_sound": "",
                        "record_template": "",
                        "time_base_score": "queue",
                        "tier_rules_apply": false,
                        "tier_rule_wait_second": 300,
                        "tier_rule_wait_multiply_level": true,
                        "tier_rule_no_agent_no_wait": false,
                        "discard_abandoned_after": 14400,
                        "abandoned_resume_allowed": true,
                        "max_wait_time": 0,
                        "max_wait_time_with_no_agent": 120,
                        "max_wait_time_with_no_agent_time_reached": 5,
                        "created_date": "2013-10-23T12:34:20.157Z",
                        "updated_date": "2013-10-23T12:34:20.157Z"
                    }
                ]
            }

    **Update**:

        CURL Usage::

            curl -u username:password --dump-header - -H "Content-Type: application/json" -X PUT --data '{"name": "change name"}' http://localhost:8000/rest-api/queue/%dqueue-id%/

        Response::

            HTTP/1.0 202 NO CONTENT
            Date: Fri, 23 Sep 2011 06:46:12 GMT
            Server: WSGIServer/0.1 Python/2.7.1+
            Vary: Accept-Language, Cookie
            Content-Length: 0
            Content-Type: text/html; charset=utf-8
            Content-Language: en-us
    """
    manager = serializers.Field(source='manager')

    class Meta:
        model = Queue
Exemple #9
0
class EmbeddedContactSerializer(ContactSerializer):
    identity = serializers.Field(required=False, write_only=True)

    class Meta:
        fields = ('identity', 'context')
Exemple #10
0
class PassageSerializer(serializers.ModelSerializer):
    owner = serializers.Field(source='user.username')

    class Meta:
        model = Passage
        fields = ('id', 'owner', 'user', 'date_created', 'passage_data')
Exemple #11
0
class UserSerializers(serializers.ModelSerializer):
    users = serializers.Field('username', read_only=True)

    class Meta:
        model = Users
        fields = ('username ', )
class DetailPaginationSerializer(pagination.PaginationSerializer):
    per_page = serializers.Field(source='paginator.per_page')
    page_count = serializers.Field(source='paginator.num_pages')
Exemple #13
0
    def __init__(self, hybrid, contents=None, depth=None, *args, **kwargs):
        """
        Initializes the serializer, mapping field types
        :param hybrid: Hybrid object to serialize
        :type hybrid: any (ovs.dal.hybrids.X.X)
        :param contents: Contents to serialize. Without contents, only the GUID is serialized
        When contents is given, all non-dynamic properties are serialized
        Further options are:
        - _dynamics: Include all dynamic properties
        - _relations: Include foreign keys and lists of primary keys of linked objects
        - _relations_contents: Apply the contents to the relations. The relation contents can be a bool or a new contents item
          - If the relations_contents=re-use: the current contents are also applied to the relation object
          - If the relations_contents=contents list: That item is subjected to the same rules as other contents
        - _relation_contents_RELATION_NAME: Apply the contents the the given relation. Same rules as _relation_contents apply here
        _ _relations_depth: Depth of relational serialization. Defaults to 1 when relation_contents were specified.
        Specifying a form of _relations_contents change the depth to 1 (if depth was 0) as the relation is to be serialized
        Specifying it 2 with _relations_contents given will serialize the relations of the fetched relation. This causes a chain of serializations
        - dynamic_property_1,dynamic_property_2 (results in static properties plus 2 dynamic properties)
        Properties can also be excluded by prefixing the field with '-':
        - contents=_dynamic,-dynamic_property_2,_relations (static properties, all dynamic properties except for dynamic_property_2 plus all relations)
        Relation serialization can be done by asking for it:
        - contents=_relations,_relations_contents=re-use
        All relational serialization can only be used to get data. This data will be not be set-able when deserializing
        :type contents: list or none
        :param depth: Current depth of serializing, used to serialize relations
        :type depth: int
        Kwarg parameters:
        :param allow_passwords: Allow the attr 'password' to be serialized
        :type allow_passwords: bool
        Parent parameters:
        :param instance: Instance of the object to use for updating
        :type instance: an
        :param data: Initialization data (Will be applied to the instance if an instance is given)
        :type data: list[dict] or dict
        :param many: Indicate that the given instance is to be iterated for serialization
        :type many: bool
        """
        if not isinstance(contents, ContentOptions):
            contents = ContentOptions(contents)
        allow_passwords = kwargs.pop('allow_passwords', False)
        super(FullSerializer, self).__init__(*args, **kwargs)
        self.hybrid = hybrid
        for prop in self.hybrid._properties:
            if 'password' not in prop.name or allow_passwords:
                self.fields[prop.name] = FullSerializer._map_type_to_field(
                    prop.property_type)
        for dynamic in self.hybrid._dynamics:
            if contents.has_content is False or (
                ('_dynamics' in contents or dynamic.name in contents)
                    and '-{0}'.format(dynamic.name) not in contents):
                self.fields[dynamic.name] = serializers.Field()
        for relation in self.hybrid._relations:
            if contents.has_content is False or (
                ('_relations' in contents or relation.name in contents)
                    and '-{0}'.format(relation.name) not in contents):
                self.fields['{0}_guid'.format(
                    relation.name)] = serializers.CharField(required=False)
        foreign_relations = RelationMapper.load_foreign_relations(
            hybrid
        )  # To many side of things, items pointing towards this object
        if foreign_relations is not None:
            for key, info in foreign_relations.iteritems():
                if contents.has_content is False or (
                    ('_relations' in contents or key in contents)
                        and '-{0}'.format(key) not in contents):
                    if info['list'] is True:
                        self.fields['%s_guids' % key] = serializers.Field()
                    else:
                        self.fields['%s_guid' % key] = serializers.Field()

        # Check is a relation needs to be serialized
        foreign_relations = RelationMapper.load_foreign_relations(
            hybrid
        )  # To many side of things, items pointing towards this object
        if contents.has_content is False or (foreign_relations is None and len(
                hybrid._relations) == 0) or depth == 0:
            return
        # Foreign relations is a dict, relations is a relation object, need to differentiate
        relation_contents = contents.get_option('_relations_contents')
        relation_contents_options = copy.deepcopy(
            contents) if relation_contents == 're-use' else ContentOptions(
                relation_contents)
        relations_data = {
            'foreign': foreign_relations or {},
            'own': hybrid._relations
        }
        for relation_type, relations in relations_data.iteritems():
            for relation in relations:
                relation_key = relation.name if relation_type == 'own' else relation
                relation_hybrid = relation.foreign_type if relation_type == 'own' else Descriptor(
                ).load(relations[relation]['class']).get_object()
                # Possible extra content supplied for a relation
                relation_content = contents.get_option(
                    '_relation_contents_{0}'.format(relation_key))
                if relation_content is None and relation_contents == 're-use':
                    relation_content_options = relation_contents_options
                else:
                    relation_content_options = ContentOptions(relation_content)
                # Use the depth given by the contents when it's the first item to serialize
                relation_depth = contents.get_option(
                    '_relations_depth',
                    1 if relation_content_options.has_content else
                    0) if depth is None else depth
                if relation_depth is None:  # Can be None when no value is give to _relations_depth
                    relation_depth = 0
                if relation_depth == 0:
                    continue
                # @Todo prevent the same one-to-one relations from being serialized multiple times? Not sure if helpful though
                self.fields[relation_key] = FullSerializer(
                    relation_hybrid,
                    contents=relation_content_options,
                    depth=relation_depth - 1)
Exemple #14
0
class FullSerializer(serializers.Serializer):
    """
    Serializes the persistent and dynamic stack of a hybrid object
    """
    guid = serializers.Field()  # Always include the GUID

    class Meta(object):
        """
        Meta class. Holds some information about the serializer
        - fields: Fields which included by default (can be edited by using the 'fields' attr in the serializer
        - read_only_fields: Indicates which fields are read only (can be edited by using the 'read_only_fields' attr in the serializer
        """
        fields = ('guid', )
        read_only_fields = ('guid', )

    def __init__(self, hybrid, contents=None, depth=None, *args, **kwargs):
        """
        Initializes the serializer, mapping field types
        :param hybrid: Hybrid object to serialize
        :type hybrid: any (ovs.dal.hybrids.X.X)
        :param contents: Contents to serialize. Without contents, only the GUID is serialized
        When contents is given, all non-dynamic properties are serialized
        Further options are:
        - _dynamics: Include all dynamic properties
        - _relations: Include foreign keys and lists of primary keys of linked objects
        - _relations_contents: Apply the contents to the relations. The relation contents can be a bool or a new contents item
          - If the relations_contents=re-use: the current contents are also applied to the relation object
          - If the relations_contents=contents list: That item is subjected to the same rules as other contents
        - _relation_contents_RELATION_NAME: Apply the contents the the given relation. Same rules as _relation_contents apply here
        _ _relations_depth: Depth of relational serialization. Defaults to 1 when relation_contents were specified.
        Specifying a form of _relations_contents change the depth to 1 (if depth was 0) as the relation is to be serialized
        Specifying it 2 with _relations_contents given will serialize the relations of the fetched relation. This causes a chain of serializations
        - dynamic_property_1,dynamic_property_2 (results in static properties plus 2 dynamic properties)
        Properties can also be excluded by prefixing the field with '-':
        - contents=_dynamic,-dynamic_property_2,_relations (static properties, all dynamic properties except for dynamic_property_2 plus all relations)
        Relation serialization can be done by asking for it:
        - contents=_relations,_relations_contents=re-use
        All relational serialization can only be used to get data. This data will be not be set-able when deserializing
        :type contents: list or none
        :param depth: Current depth of serializing, used to serialize relations
        :type depth: int
        Kwarg parameters:
        :param allow_passwords: Allow the attr 'password' to be serialized
        :type allow_passwords: bool
        Parent parameters:
        :param instance: Instance of the object to use for updating
        :type instance: an
        :param data: Initialization data (Will be applied to the instance if an instance is given)
        :type data: list[dict] or dict
        :param many: Indicate that the given instance is to be iterated for serialization
        :type many: bool
        """
        if not isinstance(contents, ContentOptions):
            contents = ContentOptions(contents)
        allow_passwords = kwargs.pop('allow_passwords', False)
        super(FullSerializer, self).__init__(*args, **kwargs)
        self.hybrid = hybrid
        for prop in self.hybrid._properties:
            if 'password' not in prop.name or allow_passwords:
                self.fields[prop.name] = FullSerializer._map_type_to_field(
                    prop.property_type)
        for dynamic in self.hybrid._dynamics:
            if contents.has_content is False or (
                ('_dynamics' in contents or dynamic.name in contents)
                    and '-{0}'.format(dynamic.name) not in contents):
                self.fields[dynamic.name] = serializers.Field()
        for relation in self.hybrid._relations:
            if contents.has_content is False or (
                ('_relations' in contents or relation.name in contents)
                    and '-{0}'.format(relation.name) not in contents):
                self.fields['{0}_guid'.format(
                    relation.name)] = serializers.CharField(required=False)
        foreign_relations = RelationMapper.load_foreign_relations(
            hybrid
        )  # To many side of things, items pointing towards this object
        if foreign_relations is not None:
            for key, info in foreign_relations.iteritems():
                if contents.has_content is False or (
                    ('_relations' in contents or key in contents)
                        and '-{0}'.format(key) not in contents):
                    if info['list'] is True:
                        self.fields['%s_guids' % key] = serializers.Field()
                    else:
                        self.fields['%s_guid' % key] = serializers.Field()

        # Check is a relation needs to be serialized
        foreign_relations = RelationMapper.load_foreign_relations(
            hybrid
        )  # To many side of things, items pointing towards this object
        if contents.has_content is False or (foreign_relations is None and len(
                hybrid._relations) == 0) or depth == 0:
            return
        # Foreign relations is a dict, relations is a relation object, need to differentiate
        relation_contents = contents.get_option('_relations_contents')
        relation_contents_options = copy.deepcopy(
            contents) if relation_contents == 're-use' else ContentOptions(
                relation_contents)
        relations_data = {
            'foreign': foreign_relations or {},
            'own': hybrid._relations
        }
        for relation_type, relations in relations_data.iteritems():
            for relation in relations:
                relation_key = relation.name if relation_type == 'own' else relation
                relation_hybrid = relation.foreign_type if relation_type == 'own' else Descriptor(
                ).load(relations[relation]['class']).get_object()
                # Possible extra content supplied for a relation
                relation_content = contents.get_option(
                    '_relation_contents_{0}'.format(relation_key))
                if relation_content is None and relation_contents == 're-use':
                    relation_content_options = relation_contents_options
                else:
                    relation_content_options = ContentOptions(relation_content)
                # Use the depth given by the contents when it's the first item to serialize
                relation_depth = contents.get_option(
                    '_relations_depth',
                    1 if relation_content_options.has_content else
                    0) if depth is None else depth
                if relation_depth is None:  # Can be None when no value is give to _relations_depth
                    relation_depth = 0
                if relation_depth == 0:
                    continue
                # @Todo prevent the same one-to-one relations from being serialized multiple times? Not sure if helpful though
                self.fields[relation_key] = FullSerializer(
                    relation_hybrid,
                    contents=relation_content_options,
                    depth=relation_depth - 1)

    def get_identity(self, data):
        """
        This hook makes sure the guid is returned as primary key
        By default the serializer class will use the id key on the incoming data to determine the canonical identity of an object
        """
        return data.get('guid', None)

    def restore_object(self, attrs, instance=None):
        """
        Provides deserializing functionality for persistent properties
        Required if we want our serializer to support deserialization into fully fledged object instances.
         If we don't define this method, then deserializing data will simply return a dictionary of items.
        """
        if instance is not None:
            for prop in self.hybrid._properties:
                setattr(instance, prop.name,
                        attrs.get(prop.name, getattr(instance, prop.name)))
            for relation in self.hybrid._relations:
                guid_key = '{0}_guid'.format(relation.name)
                if guid_key in attrs and attrs[guid_key] != getattr(
                        instance, guid_key):
                    setattr(
                        instance, relation.name,
                        None if attrs[guid_key] is None else
                        relation.foreign_type(attrs[guid_key]))
            return instance
        return self.hybrid(data=attrs)

    @staticmethod
    def _map_type_to_field(field_type):
        """
        Maps the given field type to a serializer field
        """
        if isinstance(field_type, list):
            field_type = type(field_type[0])
        if field_type is str:
            return serializers.CharField(required=False)
        if field_type is int:
            return serializers.IntegerField(required=False)
        if field_type is bool:
            return serializers.BooleanField(required=False)
        if field_type is dict:
            return serializers.WritableField(required=False)
        return serializers.Field()

    def deserialize(self):
        _ = self.errors  # Trigger deserialization
        return self.object
class FullSerializer(serializers.Serializer):
    """
    Serializes the persistent and dynamic stack of a hybrid object
    """
    def __init__(self, hybrid, contents=None, *args, **kwargs):
        """
        Initializes the serializer, mapping field types
        """
        allow_passwords = False
        if 'allow_passwords' in kwargs:
            allow_passwords = kwargs['allow_passwords']
            del kwargs['allow_passwords']
        super(FullSerializer, self).__init__(*args, **kwargs)
        self.hybrid = hybrid
        for prop in self.hybrid._properties:
            if not 'password' in prop.name or allow_passwords:
                self.fields[prop.name] = FullSerializer._map_type_to_field(prop.property_type)
        for dynamic in self.hybrid._dynamics:
            if contents is None or (('_dynamics' in contents or dynamic.name in contents)
                                    and '-{0}'.format(dynamic.name) not in contents):
                self.fields[dynamic.name] = serializers.Field()
        for relation in self.hybrid._relations:
            if contents is None or (('_relations' in contents or relation.name in contents)
                                    and '-{0}'.format(relation.name) not in contents):
                self.fields['{0}_guid'.format(relation.name)] = serializers.CharField(required=False)
        relations = RelationMapper.load_foreign_relations(hybrid)
        if relations is not None:
            for key, info in relations.iteritems():
                if contents is None or (('_relations' in contents or key in contents)
                                        and '-{0}'.format(key) not in contents):
                    if info['list'] is True:
                        self.fields['%s_guids' % key] = serializers.Field()
                    else:
                        self.fields['%s_guid' % key] = serializers.Field()

    guid = serializers.Field()

    def get_identity(self, data):
        """
        This hook makes sure the guid is returned as primary key
        """
        return data.get('guid', None)

    def restore_object(self, attrs, instance=None):
        """
        Provides deserializing functionality for persistent properties
        """
        if instance is not None:
            for prop in self.hybrid._properties:
                setattr(instance, prop.name, attrs.get(prop.name, getattr(instance, prop.name)))
            for relation in self.hybrid._relations:
                guid_key = '{0}_guid'.format(relation.name)
                if guid_key in attrs and attrs[guid_key] != getattr(instance, guid_key):
                    setattr(instance, relation.name, None if attrs[guid_key] is None else relation.foreign_type(attrs[guid_key]))
            return instance
        return self.hybrid(data=attrs)

    @staticmethod
    def _map_type_to_field(field_type):
        """
        Maps the given field type to a serializer field
        """
        if isinstance(field_type, list):
            field_type = type(field_type[0])
        if field_type is str:
            return serializers.CharField(required=False)
        if field_type is int:
            return serializers.IntegerField(required=False)
        if field_type is bool:
            return serializers.BooleanField(required=False)
        return serializers.Field()

    class Meta:
        """
        Meta class
        """
        fields = ('guid',)
        read_only_fields = ('guid',)
Exemple #16
0
class NewsSerializer(ImagableModelSerializer, serializers.ModelSerializer):
    """
    News serializer - API endpoint for news Backbone application.
    """
    id = serializers.Field(source='pk')
    title = serializers.CharField(max_length=64)
    slug = serializers.SlugField(required=False)
    link = serializers.Field(source='get_absolute_url')
    content = serializers.Field(source='get_entry_introtext')
    date_created = serializers.DateTimeField(required=False)
    date_edited = serializers.DateTimeField(required=False)
    username = serializers.Field(source='creator.username')
    user_id = serializers.Field(source='creator.pk')
    user_full_name = serializers.Field(source='creator.get_full_name')
    avatar = serializers.Field(source='creator.profile.avatar.url')
    creator_url = serializers.Field(source='creator.profile.get_absolute_url')
    location = serializers.PrimaryKeyRelatedField(read_only=True)
    category = serializers.RelatedField()
    category_url = serializers.SerializerMethodField('category_search_url')
    edited = serializers.BooleanField()
    tags = serializers.SerializerMethodField('get_tags')
    comment_count = serializers.SerializerMethodField('get_comment_count')
    comment_meta = serializers.SerializerMethodField('get_comment_meta')

    class Meta:
        model = News
        fields = (
            'id',
            'title',
            'slug',
            'link',
            'content',
            'date_created',
            'date_edited',
            'username',
            'user_id',
            'avatar',
            'location',
            'category',
            'category_url',
            'edited',
            'tags',
            'comment_count',
            'user_full_name',
            'creator_url',
            'comment_meta',
            'image',
        )

    def get_tags(self, obj):
        tags = []
        for tag in obj.tags.all():
            tags.append({
                'name':
                tag.name,
                'url':
                reverse('locations:tag_search',
                        kwargs={
                            'slug': obj.location.slug,
                            'tag': tag.slug
                        })
            })
        return tags

    def get_comment_meta(self, obj):
        return {
            'content-type': ContentType.objects.get_for_model(News).pk,
            'content-label': 'blog',
        }

    def get_comment_count(self, obj):
        pk = obj.pk
        content_type = ContentType.objects.get_for_model(obj)
        comments = CustomComment.objects.filter(content_type=content_type)
        return len(comments.filter(object_pk=pk))

    def category_search_url(self, obj):
        if obj.category is not None:
            return reverse('locations:category_search',
                           kwargs={
                               'slug': obj.location.slug,
                               'app': 'blog',
                               'model': 'news',
                               'category': obj.category.pk
                           })
        return u""
class FollowerListSerializer(serializers.ModelSerializer):
    user_self = serializers.Field(source='to_json_self')

    class Meta:
        model = SocialFriendShip
        fields = ('id', 'user_self', 'user_obj', 'type')
Exemple #18
0
class MyActionsSerializer(serializers.Serializer):
    """
    Serializer for user activity stream.
    """
    id = serializers.Field(source='pk')
    verb = serializers.Field()
    timestamp = serializers.SerializerMethodField('get_timestamp')
    actor = serializers.SerializerMethodField('get_actor_data')
    object = serializers.SerializerMethodField('get_action_object')
    object_ct = serializers.SerializerMethodField('get_verbose_name')
    target = serializers.SerializerMethodField('get_action_target')
    target_ct = serializers.Field(source='target_content_type.model')
    description = serializers.SerializerMethodField('get_action_description')

    def get_timestamp(self, obj):
        return obj.timestamp.isoformat()

    def get_verbose_name(self, obj):
        try:
            ct = obj.action_object_content_type
            target = ct.get_object_for_this_type(
                pk=obj.action_object_object_id)
            return target._meta.verbose_name
        except Exception:
            return u''

    def get_object_url(self, obj):
        try:
            ct = obj.action_object_content_type
            target = ct.get_object_for_this_type(
                pk=obj.action_object_object_id)
            return target.get_absolute_url()
        except Exception:
            return u''

    def serialize_selected_object(self, content_type, instance):
        """ 
        Factory method to get serialized data for passed objects. It use's
        basic serializers if possible.
        """
        if content_type.model == 'location':
            serializer = LocationBasicSerializer(instance)
            return serializer.data
        elif content_type.model == 'news':
            serializer = NewsBasicSerializer(instance)
            return serializer.data
        elif content_type.model == 'idea':
            serializer = IdeaBasicSerializer(instance)
            return serializer.data
        elif content_type.model == 'poll':
            serializer = PollBasicSerializer(instance)
            return serializer.data
        elif content_type.model == 'locationgalleryitem':
            serializer = GalleryItemSerializer(instance)
            return serializer.data
        elif content_type.model == 'discussion':
            serializer = DiscussionSerializer(instance)
            serializer.data['name'] = serializer.data['question']
            return serializer.data
        elif content_type.model == 'socialproject':
            serializer = ProjectActionSerializer(instance)
            return serializer.data
        elif content_type.model == 'taskgroup':
            serializer = TaskGroupActionSerializer(instance)
            return serializer.data
        elif content_type.model == 'task':
            serializer = TaskActionSerializer(instance)
            return serializer.data
        else:
            data = {
                'id': instance.pk,
                'url': self.get_object_url(instance),
            }
            return data

    def get_action_description(self, obj):
        try:
            ct = obj.action_object_content_type
            target = ct.get_object_for_this_type(
                pk=obj.action_object_object_id)
            if obj.verb == 'commented':
                return '{} <a href="{}">{}</a>'.format(
                    truncatehtml(obj.data['comment'], 140),
                    obj.data['comment_url'], _("More"))
            elif obj.verb == 'voted on':
                if obj.data['vote']:
                    return '<div class="vote-{}"><a href="{}">{}</a></div>' \
                        .format('up', target.get_absolute_url(), _("Voted yes"))
                else:
                    return '<div class="vote-{}"><a href="{}">{}</a></div>' \
                        .format('down', target.get_absolute_url(), _("Voted no"))
            elif ct.model == 'idea':
                return truncatehtml(target.description, 140)
            elif ct.model == 'location':
                return truncatehtml(target.description, 140)
            elif ct.model == 'news':
                return truncatehtml(target.content, 140)
            elif ct.model == 'poll':
                return truncatehtml(target.question, 140)
            elif ct.model == 'discussion':
                return truncatehtml(target.intro, 140)
            elif ct.model == 'entry':
                return truncatehtml(target.content, 140)
            elif ct.model == 'locationgalleryitem':
                return '<a href="' + target.get_absolute_url() + '">' + \
                    '<img src="' + target.get_thumbnail((256,256)) + '" /></a>'
            elif ct.model == 'socialproject':
                return truncatehtml(target.description, 140)
            elif ct.model == 'taskgroup':
                return truncatehtml(target.description, 140)
            elif ct.model == 'task':
                return truncatehtml(target.description, 140)
            else:
                return u''
        except Exception:
            return u''

    def get_action_object(self, obj):
        try:
            ct = obj.action_object_content_type
            target = ct.get_object_for_this_type(
                pk=obj.action_object_object_id)
            return self.serialize_selected_object(ct, target)
        except Exception:
            return {}

    def get_action_target(self, obj):
        try:
            ct = obj.target_content_type
            target = ct.get_object_for_this_type(pk=obj.target_object_id)
            return self.serialize_selected_object(ct, target)
        except Exception:
            return {}

    def get_actor_data(self, obj):
        """ WARNING: we assume that every actor is user instance!!!. """
        user = User.objects.get(pk=obj.actor_object_id)
        serializer = UserSerializer(user)
        return serializer.data
Exemple #19
0
class UserListSerializer(serializers.ModelSerializer):
    img = serializers.ImageField(allow_empty_file=True, required=False)
    full_name = serializers.Field(source="get_full_name")
    class Meta:
        model = Professional
        fields = ('id', "full_name",  "img",)
Exemple #20
0
class DiscussionSerializer(ImagableModelSerializer,
                           serializers.ModelSerializer):
    """ Basic serializer for discussions. """
    id = serializers.Field(source='pk')
    question = serializers.CharField()
    intro = serializers.CharField()
    location = serializers.PrimaryKeyRelatedField()
    url = serializers.Field(source='get_absolute_url')
    creator_id = serializers.Field(source='creator.pk')
    creator_username = serializers.Field(source='creator.username')
    creator_fullname = serializers.Field(source='creator.get_full_name')
    creator_url = serializers.Field(source='creator.profile.get_absolute_url')
    creator_avatar = serializers.Field(source='creator.profile.avatar.url')
    date_created = serializers.DateTimeField(required=False)
    date_edited = serializers.DateTimeField(required=False)
    status = serializers.BooleanField()
    category_name = serializers.Field(source='category.name')
    category_url = serializers.SerializerMethodField('category_search_url')
    tags = serializers.SerializerMethodField('get_tags')
    answers = serializers.SerializerMethodField('get_answer_count')

    class Meta:
        model = Discussion
        fields = (
            'id',
            'question',
            'intro',
            'url',
            'creator_id',
            'answers',
            'creator_fullname',
            'creator_url',
            'creator_avatar',
            'category_name',
            'date_created',
            'date_edited',
            'status',
            'category_url',
            'tags',
            'creator_username',
            'location',
            'image',
        )

    def get_tags(self, obj):
        tags = []
        for tag in obj.tags.all():
            tags.append({
                'name':
                tag.name,
                'url':
                reverse('locations:tag_search',
                        kwargs={
                            'slug': obj.location.slug,
                            'tag': tag.slug
                        })
            })
        return tags

    def category_search_url(self, obj):
        if obj.category is not None:
            return reverse('locations:category_search',
                           kwargs={
                               'slug': obj.location.slug,
                               'app': 'topics',
                               'model': 'discussion',
                               'category': obj.category.pk
                           })
        return u""

    def get_answer_count(self, obj):
        return obj.entry_set.count()
Exemple #21
0
class CreditcardSerializer(serializers.ModelSerializer):
    creditcard = serializers.Field(source='stripe_get_creditcard')

    class Meta:
        model = User
        fields = ('id', 'creditcard',)
Exemple #22
0
class IdeaSerializer(serializers.ModelSerializer):
    """ Idea serializer. """
    id = serializers.Field(source='pk')
    name = serializers.CharField()
    url = serializers.Field(source='get_absolute_url')
    description = serializers.CharField()
    creator_id = serializers.Field(source='creator.pk')
    creator_url = serializers.Field(source='creator.profile.get_absolute_url')
    creator_username = serializers.Field(source='creator.username')
    creator_fullname = serializers.Field(source='creator.get_full_name')
    creator_avatar = serializers.Field(source='creator.profile.avatar.url')
    date_created = serializers.DateTimeField(required=False)
    date_edited = serializers.DateTimeField(required=False)
    category_name = serializers.SerializerMethodField('get_category_name')
    category_url = serializers.SerializerMethodField('category_search_url')
    total_comments = serializers.Field(source='get_comment_count')
    total_votes = serializers.Field(source='get_votes')
    edited = serializers.BooleanField()
    tags = serializers.SerializerMethodField('get_tags')
    comment_meta = serializers.SerializerMethodField('get_comment_meta')
    image = serializers.Field(source='image_url')

    class Meta:
        model = Idea
        fields = ('id', 'name', 'description', 'creator_id',
                  'creator_username', 'creator_fullname', 'creator_avatar',
                  'date_created', 'date_edited', 'edited', 'tags',
                  'category_name', 'category_url', 'total_comments',
                  'total_votes', 'url', 'creator_url', 'comment_meta', 'image')

    def get_comment_meta(self, obj):
        return {
            'content-type': ContentType.objects.get_for_model(Idea).pk,
            'content-label': 'ideas',
        }

    def get_tags(self, obj):
        tags = []
        for tag in obj.tags.all():
            tags.append({
                'name':
                tag.name,
                'url':
                reverse('locations:tag_search',
                        kwargs={
                            'slug': obj.location.slug,
                            'tag': tag.slug
                        })
            })
        return tags

    def category_search_url(self, obj):
        if obj.category:
            return reverse('locations:category_search',
                           kwargs={
                               'slug': obj.location.slug,
                               'app': 'topics',
                               'model': 'discussion',
                               'category': obj.category.pk
                           })
        return r''

    def get_category_name(self, obj):
        if obj.category:
            return obj.category.name
        return u''
Exemple #23
0
class SlugSerializer(serializers.ModelSerializer):
    slug = serializers.Field()  # read only

    class Meta:
        model = SlugBasedModel
        exclude = ('id', )
Exemple #24
0
class EnvironmentVipV3Serializer(DynamicFieldsModelSerializer):
    """Serilizes EnvironmentVip Model."""

    name = serializers.Field(source='name')

    optionsvip = serializers.SerializerMethodField('get_optionsvip')
    environments = serializers.SerializerMethodField('get_environments')

    def get_optionsvip(self, obj):

        return self.extends_serializer(obj, 'optionsvip')

    def get_environments(self, obj):
        return self.extends_serializer(obj, 'environments')

    class Meta:
        EnvironmentVip = get_model('ambiente', 'EnvironmentVip')
        model = EnvironmentVip
        fields = (
            'id',
            'finalidade_txt',
            'cliente_txt',
            'ambiente_p44_txt',
            'description',
            'name',
            'conf',
            'optionsvip',
            'environments',
        )

        default_fields = (
            'id',
            'finalidade_txt',
            'cliente_txt',
            'ambiente_p44_txt',
            'description',
        )

        details_fields = (
            'id',
            'finalidade_txt',
            'cliente_txt',
            'ambiente_p44_txt',
            'description',
            'name',
            'conf',
        )

        basic_fields = (
            'id',
            'name',
        )

    def get_serializers(self):
        """Returns the mapping of serializers."""

        if not self.mapping:
            self.mapping = {
                'optionsvip': {
                    'serializer': OptionVipEnvironmentVipV3Serializer,
                    'kwargs': {
                        'many': True,
                        'fields': ('option', )
                    },
                    'obj': 'optionsvip',
                },
                'environments': {
                    'serializer': EnvironmentEnvironmentVipV3Serializer,
                    'kwargs': {
                        'many': True,
                        'fields': ('environment', )
                    },
                    'obj': 'environments',
                },
                'optionsvip__details': {
                    'serializer': OptionVipEnvironmentVipV3Serializer,
                    'kwargs': {
                        'many': True,
                        'kind': 'details',
                        'fields': ('option', )
                    },
                    'obj': 'optionsvip',
                },
                'environments__details': {
                    'serializer': EnvironmentEnvironmentVipV3Serializer,
                    'kwargs': {
                        'many': True,
                        'kind': 'details',
                        'fields': ('environment', )
                    },
                    'obj': 'environments',
                },
            }
class IndicatorSerializer(ModelSerializer):
    creator_path = serializers.Field(source='creator_path')

    class Meta:
        model = Indicator
Exemple #26
0
class ReviewersESAppSerializer(ESAppSerializer):
    latest_version = serializers.Field(source='es_data.latest_version')
    is_escalated = serializers.BooleanField()

    class Meta(ESAppSerializer.Meta):
        fields = SEARCH_FIELDS + ['latest_version', 'is_escalated']
Exemple #27
0
class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
    username = serializers.WritableField(source='user.username')
    email = serializers.WritableField(source='user.email')
    website = serializers.WritableField(source='home_page', required=False)
    gravatar = serializers.Field(source='gravatar')
    password = serializers.WritableField(
        source='user.password', widget=widgets.PasswordInput(), required=False)
    user = serializers.HyperlinkedRelatedField(
        view_name='user-detail', lookup_field='username', read_only=True)

    class Meta:
        model = UserProfile
        fields = ('url', 'username', 'name', 'password', 'email', 'city',
                  'country', 'organization', 'website', 'twitter', 'gravatar',
                  'require_auth', 'user')
        lookup_field = 'user'

    def to_native(self, obj):
        """
        Serialize objects -> primitives.
        """
        ret = super(UserProfileSerializer, self).to_native(obj)
        if 'password' in ret:
            del ret['password']
        return ret

    def restore_object(self, attrs, instance=None):
        def _get_first_last_names(name):
            name_split = name.split()
            first_name = name_split[0]
            last_name = u''
            if len(name_split) > 1:
                last_name = u' '.join(name_split[1:])
            return first_name, last_name
        params = copy.deepcopy(attrs)
        username = attrs.get('user.username', None)
        password = attrs.get('user.password', None)
        name = attrs.get('name', None)
        email = attrs.get('user.email', None)
        if username:
            params['username'] = username
        if email:
            params['email'] = email
        if password:
            params.update({'password1': password, 'password2': password})
        if instance:
            form = UserProfileForm(params, instance=instance)
            # form.is_valid affects instance object for partial updates [PATCH]
            # so only use it for full updates [PUT], i.e shallow copy effect
            if not self.partial and form.is_valid():
                instance = form.save()
            # get user
            if email:
                instance.user.email = form.cleaned_data['email']
            if name:
                first_name, last_name = _get_first_last_names(name)
                instance.user.first_name = first_name
                instance.user.last_name = last_name
            if email or name:
                instance.user.save()
            return super(
                UserProfileSerializer, self).restore_object(attrs, instance)
            #return instance  # TODO: updates
        form = RegistrationFormUserProfile(params)
        # does not require captcha
        form.REGISTRATION_REQUIRE_CAPTCHA = False
        if form.is_valid():
            first_name, last_name = _get_first_last_names(name)
            new_user = User(username=username, first_name=first_name,
                            last_name=last_name, email=email)
            new_user.set_password(password)
            new_user.save()
            created_by = self.context['request'].user
            profile = UserProfile(
                user=new_user, name=attrs.get('name', u''),
                created_by=created_by,
                city=attrs.get('city', u''),
                country=attrs.get('country', u''),
                organization=attrs.get('organization', u''),
                home_page=attrs.get('home_page', u''),
                twitter=attrs.get('twitter', u''))
            return profile
        else:
            self.errors.update(form.errors)
        return attrs
class InstallationStepSerializer(serializers.ModelSerializer):
    version = RequiredPackageVersionSerializer()
    progress = serializers.Field(source='get_progress')
    class Meta:
        model = PackageInstallationStep
        fields = ('id', 'version', 'previous_version', 'action', 'status', 'progress', 'log', 'created', 'modified','order')
Exemple #29
0
class WMSLayerSerializer(serializers.HyperlinkedModelSerializer):
    url = serializers.HyperlinkedIdentityField(view_name='layer-detail')

    styles = JSONField('styles', '_params')
    format = JSONField('format', '_params')
    height = JSONField('height', '_params')
    width = JSONField('width', '_params')
    tiled = JSONField('tiled', '_params')
    transparent = JSONField('transparent', '_params')

    opacity = serializers.SerializerMethodField('get_opacity')
    type = serializers.SerializerMethodField('get_type')

    options = serializers.SerializerMethodField('get_options')
    legend_url = serializers.SerializerMethodField('get_legend_url')

    wms_url = serializers.Field('url')

    def get_wms_url(self, obj):
        return obj.url

    def get_opacity(self, obj):
        options = obj.options
        if isinstance(options, basestring):
            try:
                options = json.loads(options)
            except ValueError:
                options = {}
        return getattr(options, 'opacity', None)

    def get_options(self, obj):
        if isinstance(obj.options, basestring):
            try:
                return json.loads(obj.options)
            except ValueError:
                return {}

    def get_legend_url(self, obj):

        # Our raster server does not yet support legends.
        # Return None if show_legend is disabled.
        if not obj.show_legend:
            return None

        if obj.legend_url:
            # use the overridden custom legend URL
            return obj.legend_url
        else:
            # automagically build GeoServer compatible legend URL
            return ('{0}'
                    '?REQUEST=GetLegendGraphic'
                    '&VERSION=1.0.0'
                    '&FORMAT=image/png'
                    '&WIDTH=20&HEIGHT=20'
                    '&LAYER={1}').format(obj.url, obj.layer_name)

    def get_type(self, obj):
        return 'wms'

    class Meta:
        model = WMSSource
        fields = ('layer_name', 'display_name', 'url', 'description',
                  'metadata', 'legend_url', 'enable_search', 'styles',
                  'format', 'height', 'width', 'tiled', 'transparent',
                  'wms_url', 'opacity', 'type', 'options')
Exemple #30
0
class EntrySerializer(serializers.ModelSerializer):
    created_on = serializers.Field(source='get_utc_created_on')

    class Meta:
        model = Entry
        fields = ('data', 'created_on')