Exemplo n.º 1
0
    def test_dehydrate(self):
        note = Note.objects.get(pk=1)
        bundle = Bundle(obj=note)

        field_1 = ListField(default=[1, 2, 3])
        self.assertEqual(field_1.dehydrate(bundle), [1, 2, 3])

        field_2 = ListField(default=['abc'])
        self.assertEqual(field_2.dehydrate(bundle), ['abc'])
Exemplo n.º 2
0
class TaskResource(ModelResource):
    pcap_file = Base64FileField("pcap_file", use_in=is_post)
    user = ForeignKey(UserResource, 'user', full=True)
    results = ListField(attribute='results',
                        null=True,
                        blank=True,
                        default=None)

    def obj_create(self, bundle, **kwargs):
        return super(TaskResource, self).obj_create(bundle,
                                                    user=bundle.request.user)

    def alter_list_data_to_serialize(self, request, data):
        for item in data['objects']:
            item.data['filename'] = os.path.basename(
                Task.objects.get(pk=item.data['id']).pcap_file.name)
        return data

    class Meta:
        queryset = Task.objects.all().order_by('-id')
        resource_name = 'task'
        allowed_methods = ['get', 'post']
        authentication = MultiAuthentication(BasicAuthentication(),
                                             ApiKeyAuthentication(),
                                             SessionAuthentication())
        authorization = CertegoDjangoAuthorization()
        filtering = {
            'submitted_on': ALL,
            'user': ALL,
            'status': ALL,
        }
        ordering = ['id', 'submitted_on', 'status']
Exemplo n.º 3
0
class ResultResource(PresentationMediumResource):

    # Returns the results of the DbEntity query
    query = ListField(attribute='query', null=False)

    class Meta(PresentationMediumResource.Meta):
        resource_name = 'result'
        always_return_data = True
        queryset = Result.objects.all()
Exemplo n.º 4
0
class BackendResource(ModelResource):
    dc = fields.ForeignKey(DcResource, 'dc', full=True)
    director = fields.ForeignKey(DirectorResource, 'director')
    tags = ListField()

    class Meta:
        queryset = Backend.objects.all()
        resource_name = 'backend'
        serializer = PrettyJSONSerializer()
        authorization = Authorization()
        authentication = ApiKeyAuthentication()
        validation = ModelCleanedDataFormValidation(
            form_class=BackendModelForm)
        filtering = {
            'dc': ALL_WITH_RELATIONS,
            'director': ALL_WITH_RELATIONS,
            'address': ['exact'],
            'port': ['exact']
        }

    def dehydrate(self, bundle):
        status = BackendStatus.objects.filter(address=bundle.data['address'],
                                              port=bundle.data['port'])
        if len(status) > 0:
            bundle.data['status'] = status[0].status
        else:
            bundle.data['status'] = "Unknown"
        return bundle

    def build_filters(self, filters=None):
        if filters is None:
            filters = {}

        orm_filters = super(BackendResource, self).build_filters(filters)

        if 'tag' in filters:
            orm_filters['tags__name__in'] = filters['tag'].split(',')
        return orm_filters

    def dehydrate_tags(self, bundle):
        return map(str, bundle.obj.tags.all())

    def hydrate_tags(self, bundle):
        if isinstance(bundle.data.get('tags'), list):
            bundle.data['tags'] = ','.join(bundle.data['tags'])
        elif bundle.data.get('tags') is None:
            bundle.data['tags'] = ''
        return bundle

    def save_m2m(self, bundle):
        tags = bundle.data.get('tags', [])
        bundle.obj.tags.set(*tags)
        return super(BackendResource, self).save_m2m(bundle)
Exemplo n.º 5
0
class StyleAttributeResource(FootprintResource):

    style_value_contexts = ListField(attribute='style_value_contexts', null=True, blank=True, default=lambda:{})

    def full_hydrate(self, bundle):
        """
            Sets the style value contexts
        :param bundle:
        :return:
        """
        if hasattr(bundle.obj, 'style_value_contexts'):
            bundle = super(StyleAttributeResource, self).full_hydrate(bundle)
            bundle.obj.style_value_contexts = bundle.data['style_value_contexts']
        return bundle

    class Meta(FootprintResource.Meta):
        always_return_data = True
        queryset = StyleAttribute.objects.all()
Exemplo n.º 6
0
class TaggableResource(BaseResource):
    """docstring for TaggableResource"""
    tags = ListField()

    def dehydrate_tags(self, bundle):
        return map(str, bundle.obj.tags.all())

    def save_m2m(self, bundle):
        tags = bundle.data.get('tags', [])
        bundle.obj.tags.set(*tags)
        return super(TaggableResource, self).save_m2m(bundle)

    def build_filters(self, filters=None, ignore_bad_filters=True):
        if filters is None:
            filters = {}

        orm_filters = super(TaggableResource, self).build_filters(filters)

        if 'tag' in filters:
            orm_filters['tags__name__in'] = filters['tag'].split(',')

        return orm_filters
Exemplo n.º 7
0
class TaggedResource(ModelResource):
    tags = ListField()

    class Meta:
        queryset = Model.objects.all()

    def build_filters(self, filters=None):
        if filters is None:
            filters = {}

        orm_filters = super(TaggedResource, self).build_filters(filters)

        if 'tag' in filters:
            orm_filters['tags__name__in'] = filters['tag'].split(',')
        return orm_filters

    def dehydrate_tags(self, bundle):
        return map(str, bundle.obj.tags.all())

    def save_m2m(self, bundle):
        tags = bundle.data.get('tags', [])
        bundle.obj.tags.set(*tags)
        return super(TaggedResource, self).save_m2m(bundle)
Exemplo n.º 8
0
class PrivateSniptResource(ModelResource):
    user = fields.ForeignKey(PrivateUserResource, "user", full=True)
    last_user_saved = fields.ForeignKey(
        PrivateUserResource, "last_user_saved", null=True, full=False
    )
    tags_list = ListField()
    tags = fields.ToManyField(PublicTagResource, "tags", related_name="tag", full=True)

    class Meta:
        queryset = Snipt.objects.all().order_by("-created")
        resource_name = "snipt"
        fields = [
            "id",
            "title",
            "slug",
            "lexer",
            "code",
            "description",
            "line_count",
            "stylized",
            "key",
            "public",
            "secure",
            "blog_post",
            "created",
            "modified",
            "publish_date",
            "meta",
        ]
        include_absolute_url = True
        detail_allowed_methods = ["get", "patch", "put", "delete"]
        list_allowed_methods = ["get", "post"]
        authentication = ApiKeyAuthentication()
        authorization = PrivateSniptAuthorization()
        validation = SniptValidation()
        ordering = ["created", "modified"]
        always_return_data = True
        max_limit = 200
        cache = SimpleCache()

    def dehydrate(self, bundle):
        bundle.data["embed_url"] = bundle.obj.get_embed_url()
        bundle.data["raw_url"] = bundle.obj.get_raw_url()
        bundle.data["tags_list"] = edit_string_for_tags(bundle.obj.tags.all())
        bundle.data["full_absolute_url"] = bundle.obj.get_full_absolute_url()
        bundle.data["description_rendered"] = linebreaksbr(
            urlize(bundle.obj.description)
        )
        bundle.data["views"] = bundle.obj.views
        bundle.data["favs"] = bundle.obj.favs()

        if bundle.data["publish_date"]:
            bundle.data["publish_date"] = date(
                bundle.data["publish_date"], "M d, Y \\a\\t h:i A"
            )

        log_entries = bundle.obj.sniptlogentry_set.all()
        bundle_log_entries = []

        for entry in log_entries:
            bundle_log_entries.append(
                {
                    "created": entry.created,
                    "user": entry.user,
                    "code": entry.code,
                    "diff": entry.diff,
                }
            )

        bundle.data["log_entries"] = bundle_log_entries

        return bundle

    def obj_create(self, bundle, **kwargs):
        bundle.data["last_user_saved"] = bundle.request.user
        bundle.data["tags_list"] = bundle.data.get("tags")
        bundle.data["tags"] = []

        if "intended_user" in bundle.data:
            bundle.data["user"] = User.objects.get(
                username=bundle.data["intended_user"]
            )
        else:
            bundle.data["user"] = bundle.request.user

        if "blog_post" in bundle.data:
            bundle = self._clean_publish_date(bundle)

        return super(PrivateSniptResource, self).obj_create(bundle, **kwargs)

    def obj_update(self, bundle, **kwargs):

        instance = Snipt.objects.get(pk=bundle.data["id"])

        if instance.user.profile.is_a_team:
            user = instance.user
        else:
            user = bundle.request.user

        bundle.data["created"] = None
        bundle.data["last_user_saved"] = bundle.request.user
        bundle.data["modified"] = None
        bundle.data["user"] = user

        if type(bundle.data["tags"]) == str or type(bundle.data["tags"]) == unicode:
            bundle.data["tags_list"] = bundle.data["tags"]
        else:
            bundle.data["tags_list"] = ""
        bundle.data["tags"] = ""

        if "blog_post" in bundle.data:
            bundle = self._clean_publish_date(bundle)

        return super(PrivateSniptResource, self).obj_update(bundle, **kwargs)

    def _clean_publish_date(self, bundle):
        if bundle.data["blog_post"] and "publish_date" not in bundle.data:
            bundle.data["publish_date"] = datetime.datetime.now()
        elif bundle.data["publish_date"] == "":
            bundle.data["publish_date"] = datetime.datetime.now()
        elif bundle.data["blog_post"]:
            c = pdt.Constants()
            p = pdt.Calendar(c)
            publish_date, result = p.parse(bundle.data["publish_date"])

            if result != 0:
                publish_date = time.strftime("%Y-%m-%d %H:%M:%S", publish_date)
            else:
                publish_date = datetime.datetime.now()

            bundle.data["publish_date"] = publish_date
        elif not bundle.data["blog_post"]:
            bundle.data["publish_date"] = None

        return bundle

    def build_filters(self, filters=None, **kwargs):
        if filters is None:
            filters = {}

        orm_filters = super(PrivateSniptResource, self).build_filters(filters)

        if "tag" in filters:
            tag = Tag.objects.get(pk=filters["tag"])
            tagged_items = tag.taggit_taggeditem_items.all()
            orm_filters["pk__in"] = [i.object_id for i in tagged_items]

        # if "q" in filters:
        #     user = User.objects.get(username=filters["username"])
        #     sqs = SearchQuerySet().filter(author=user, content=filters["q"])
        #     orm_filters["pk__in"] = [i.pk for i in sqs]

        return orm_filters

    def save_m2m(self, bundle):
        tags = bundle.data.get("tags_list", [])
        if tags != "":
            bundle.obj.tags.set(*parse_tags(tags))
        else:
            bundle.obj.tags.set()
Exemplo n.º 9
0
class PrivateSniptResource(ModelResource):
    user = fields.ForeignKey(PrivateUserResource, 'user', full=True)
    last_user_saved = fields.ForeignKey(PrivateUserResource,
                                        'last_user_saved',
                                        null=True,
                                        full=False)
    tags_list = ListField()
    tags = fields.ToManyField(PublicTagResource,
                              'tags',
                              related_name='tag',
                              full=True)

    class Meta:
        queryset = Snipt.objects.all().order_by('-created')
        resource_name = 'snipt'
        fields = [
            'id', 'title', 'slug', 'lexer', 'code', 'description',
            'line_count', 'stylized', 'key', 'public', 'blog_post', 'created',
            'modified', 'publish_date', 'meta'
        ]
        include_absolute_url = True
        detail_allowed_methods = ['get', 'patch', 'put', 'delete']
        list_allowed_methods = ['get', 'post']
        authentication = ApiKeyAuthentication()
        authorization = PrivateSniptAuthorization()
        validation = SniptValidation()
        ordering = ['created', 'modified']
        always_return_data = True
        max_limit = 200
        cache = SimpleCache()

    def dehydrate(self, bundle):
        bundle.data['embed_url'] = bundle.obj.get_embed_url()
        bundle.data['raw_url'] = bundle.obj.get_raw_url()
        bundle.data['tags_list'] = edit_string_for_tags(bundle.obj.tags.all())
        bundle.data['full_absolute_url'] = bundle.obj.get_full_absolute_url()
        bundle.data['description_rendered'] = \
            linebreaksbr(urlize(bundle.obj.description))
        bundle.data['views'] = bundle.obj.views
        bundle.data['favs'] = bundle.obj.favs()

        if bundle.data['publish_date']:
            bundle.data['publish_date'] = \
                date(bundle.data['publish_date'], 'M d, Y \\a\\t h:i A')

        log_entries = bundle.obj.sniptlogentry_set.all()
        bundle_log_entries = []

        for entry in log_entries:
            bundle_log_entries.append({
                'created': entry.created,
                'user': entry.user,
                'code': entry.code,
                'diff': entry.diff
            })

        bundle.data['log_entries'] = bundle_log_entries

        return bundle

    def obj_create(self, bundle, **kwargs):
        bundle.data['last_user_saved'] = bundle.request.user
        bundle.data['tags_list'] = bundle.data.get('tags')
        bundle.data['tags'] = []

        if 'intended_user' in bundle.data:
            bundle.data['user'] = \
                User.objects.get(username=bundle.data['intended_user'])
        else:
            bundle.data['user'] = bundle.request.user

        if 'blog_post' in bundle.data:
            bundle = self._clean_publish_date(bundle)

        return super(PrivateSniptResource, self) \
            .obj_create(bundle, **kwargs)

    def obj_update(self, bundle, **kwargs):

        instance = Snipt.objects.get(pk=bundle.data['id'])

        if (instance.user.profile.is_a_team):
            user = instance.user
        else:
            user = bundle.request.user

        bundle.data['created'] = None
        bundle.data['last_user_saved'] = bundle.request.user
        bundle.data['modified'] = None
        bundle.data['user'] = user

        if type(bundle.data['tags']) == str or type(
                bundle.data['tags']) == unicode:
            bundle.data['tags_list'] = bundle.data['tags']
        else:
            bundle.data['tags_list'] = ''
        bundle.data['tags'] = ''

        if 'blog_post' in bundle.data:
            bundle = self._clean_publish_date(bundle)

        return super(PrivateSniptResource, self) \
            .obj_update(bundle, **kwargs)

    def _clean_publish_date(self, bundle):
        if bundle.data['blog_post'] and 'publish_date' not in bundle.data:
            bundle.data['publish_date'] = datetime.datetime.now()
        elif bundle.data['publish_date'] == '':
            bundle.data['publish_date'] = datetime.datetime.now()
        elif bundle.data['blog_post']:
            c = pdt.Constants()
            p = pdt.Calendar(c)
            publish_date, result = p.parse(bundle.data['publish_date'])

            if result != 0:
                publish_date = time.strftime("%Y-%m-%d %H:%M:%S", publish_date)
            else:
                publish_date = datetime.datetime.now()

            bundle.data['publish_date'] = publish_date
        elif not bundle.data['blog_post']:
            bundle.data['publish_date'] = None

        return bundle

    def build_filters(self, filters=None):
        if filters is None:
            filters = {}

        orm_filters = super(PrivateSniptResource, self).build_filters(filters)

        if 'tag' in filters:
            tag = Tag.objects.get(pk=filters['tag'])
            tagged_items = tag.taggit_taggeditem_items.all()
            orm_filters['pk__in'] = [i.object_id for i in tagged_items]

        if 'q' in filters:
            user = User.objects.get(username=filters['username'])
            sqs = SearchQuerySet().filter(author=user, content=filters['q'])
            orm_filters['pk__in'] = [i.pk for i in sqs]

        return orm_filters

    def save_m2m(self, bundle):
        tags = bundle.data.get('tags_list', [])
        if tags != '':
            bundle.obj.tags.set(*parse_tags(tags))
        else:
            bundle.obj.tags.set()
Exemplo n.º 10
0
class IntersectionsResource(Resource):
    airspaces_id = ListField(
        attribute='airspaces_id'
    )  # list of IDs of airspace intersected. Could be omitted.
    intersections = ListField(
        attribute='intersections')  # contains Intersection objects
    indexes = ListField(attribute='indexes')  # could be removed ?
    interpolated = ListField(
        attribute='interpolated')  # interpolated version of path sent by user
    relief_profile = ListField(
        attribute='relief_profile'
    )  # relief along path, using interpolated version.

    class Meta:
        resource_name = 'intersections'
        object_class = IntersectionBundle
        authentication = Authentication()
        authorization = Authorization()
        allowed_methods = ['get']
        include_resource_uri = False

    def base_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/path%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('get_path'),
                name="api_get_path"),
            url(r"^(?P<resource_name>%s)/gpx/(?P<gpxid>.*)%s$" %
                (self._meta.resource_name, trailing_slash()),
                self.wrap_view('get_gpx'),
                name="api_get_gpx"),
        ]

    def get_path(self, request, **kwargs):
        self.method_check(request, allowed=['get'])
        self.is_authenticated(request)
        self.throttle_check(request)

        q = request.GET.get('q', '').strip().split(',')
        coords = []
        for p in q:
            mq = re.match('(?P<lat>-?[\d\.]+) (?P<lon>-?[\d\.]+)', p)
            coords.append([float(mq.group('lat')), float(mq.group('lon'))])

        h = request.GET.get('h', None)
        try:
            h = float(h)
        except:
            h = None

        path = LineString(coords)
        indexes, interpolated = interpolate_linestring(path)
        relief_profile = get_relief_profile_along_track(interpolated)

        ib = get_space_intersect_path(LineString(interpolated), h)
        ib.indexes = indexes
        ib.interpolated = interpolated
        ib.relief_profile = relief_profile

        bundle = self.build_bundle(obj=ib, request=request)
        bundle = self.full_dehydrate(bundle)

        self.log_throttled_access(request)
        return self.create_response(request, bundle)

    def get_gpx(self, request, **kwargs):
        try:
            filename = kwargs.get('gpxid', None)
            dfilename = os.path.join("uploads", filename)

            track_geos = loadFromGpx(str(dfilename))
            relief_profile = get_relief_profile_along_track(track_geos)
        except:
            raise ImmediateHttpResponse(response=HttpNotFound())

        ib = get_space_intersect_path(track_geos)

        ib.indexes = [track_geos.project(Point(x)) for x in track_geos]
        ib.interpolated = []

        ib.relief_profile = relief_profile

        bundle = self.build_bundle(obj=ib, request=request)
        bundle = self.full_dehydrate(bundle)
        bundle.data['success'] = True
        bundle.data['trackURL'] = '/static/' + filename

        self.log_throttled_access(request)
        return self.create_response(request, bundle)

    def dehydrate_intersections(self, bundle):
        return [x.as_dict() for x in bundle.obj.intersections]
Exemplo n.º 11
0
class UploadedLayerResource(ModelResource):
    """
    API for accessing UploadedData.
    """

    geonode_layer = DictField(attribute='layer_data', readonly=True, null=True)
    configuration_options = DictField(attribute='configuration_options', null=True)
    fields = ListField(attribute='fields')
    status = CharField(attribute='status', readonly=True, null=True)
    file_type = CharField(attribute='file_type', readonly=True)
    file_name = CharField(attribute='file_name', readonly=True)
    layer_name = CharField(attribute='layer_name', readonly=True)

    class Meta:
        queryset = UploadLayer.objects.all()
        resource_name = 'data-layers'
        allowed_methods = ['get']
        filtering = {'id': ALL}
        authentication = SessionAuthentication()

    def get_object_list(self, request):
        """
        Filters the list view by the current user.
        """
        return super(UploadedLayerResource, self).get_object_list(request).filter(upload__user=request.user.id)

    def clean_configuration_options(self, request, obj, configuration_options):
        return configuration_options

    def import_layer(self, request, pk=None, **kwargs):
        """Imports a layer
        """
        self.method_check(request, allowed=['post'])

        bundle = Bundle(request=request)

        try:
            obj = self.obj_get(bundle, pk=pk)
        except UploadLayer.DoesNotExist:
            raise ImmediateHttpResponse(response=http.HttpNotFound())

        configuration_options = request.POST.get('configurationOptions')

        if 'application/json' in request.META.get('CONTENT_TYPE', ''):
            configuration_options = json.loads(request.body)

        if isinstance(configuration_options, list) and len(configuration_options) == 1:
            configuration_options = configuration_options[0]

        if isinstance(configuration_options, dict):
            self.clean_configuration_options(request, obj, configuration_options)
            obj.configuration_options = configuration_options
            obj.save()

        if not configuration_options:
            raise ImmediateHttpResponse(response=http.HttpBadRequest('Configuration options missing.'))

        uploaded_file = obj.upload_file

        configuration_options.update({'upload_layer_id': pk})
        import_result = import_object.delay(uploaded_file.id, configuration_options=configuration_options)

        task_id = getattr(import_result, 'id', None)
        # The task id will be useless if no backend is configured or a non-persistent backend is used.
        return self.create_response(request, {'task': task_id})

    def prepend_urls(self):
        return [url(r"^(?P<resource_name>{0})/(?P<pk>\w[\w/-]*)/configure{1}$".format(self._meta.resource_name,
                                                                                      trailing_slash()),
                self.wrap_view('import_layer'), name="importer_configure"),
                ]
Exemplo n.º 12
0
class BackendResource(ModelResource):
    dc = fields.ForeignKey(DcResource, 'dc', full=True)
    director = fields.ForeignKey(DirectorResource, 'director')
    tags = ListField()

    class Meta:
        queryset = Backend.objects\
            .select_related('director__time_profile', 'dc')\
            .prefetch_related('tags')\
            .extra(select={
                'status':
                    "SELECT status from monitor_backendstatus"
                    " WHERE monitor_backendstatus.address=manager_backend.address"
                    " AND monitor_backendstatus.port=manager_backend.port"
                    " LIMIT 1"
            })\
            .all()
        resource_name = 'backend'
        serializer = PrettyJSONSerializer()
        authorization = DjangoAuthorization()
        authentication = VaasMultiAuthentication(ApiKeyAuthentication())
        validation = ModelCleanedDataFormValidation(
            form_class=BackendModelForm)
        always_return_data = True
        filtering = {
            'dc': ALL_WITH_RELATIONS,
            'director': ALL_WITH_RELATIONS,
            'address': ['exact'],
            'port': ['exact']
        }

    def dehydrate(self, bundle):
        bundle.data['status'] = "Unknown"
        if hasattr(bundle.obj, "status") and bundle.obj.status:
            bundle.data['status'] = bundle.obj.status

        bundle.data['time_profile'] = {
            'max_connections':
            bundle.obj.director.time_profile.max_connections,
            'connect_timeout':
            bundle.obj.director.time_profile.connect_timeout,
            'first_byte_timeout':
            bundle.obj.director.time_profile.first_byte_timeout,
            'between_bytes_timeout':
            bundle.obj.director.time_profile.between_bytes_timeout
        }

        return bundle

    def build_filters(self, filters=None, ignore_bad_filters=False):
        if filters is None:
            filters = {}

        orm_filters = super(BackendResource, self).build_filters(
            filters, ignore_bad_filters=ignore_bad_filters)

        if 'tag' in filters:
            orm_filters['tags__name__in'] = filters['tag'].split(',')
        return orm_filters

    def dehydrate_tags(self, bundle):
        return list(map(str, bundle.obj.tags.all()))

    def hydrate_tags(self, bundle):
        if isinstance(bundle.data.get('tags'), list):
            bundle.data['tags'] = ','.join(bundle.data['tags'])
        elif bundle.data.get('tags') is None:
            bundle.data['tags'] = ''
        return bundle

    def save_m2m(self, bundle):
        tags = bundle.data.get('tags', [])
        bundle.obj.tags.set(*tags)
        return super(BackendResource, self).save_m2m(bundle)
Exemplo n.º 13
0
class PublisherSetResource(ProtectedModelResource):

    targetvalues_ids = ListField(use_in='detail', default=[])
    targetvalues = ToManyField(PublishersResource,
                               'targetvalues',
                               full=True,
                               use_in='detail',
                               readonly=True,
                               default=[])

    class Meta:
        resource_name = 'sets'
        list_allowed_methods = ('get', 'post')
        details_allowed_methods = ('get', 'put')
        always_return_data = True

        queryset = PublisherSet.objects.all()
        authorization = Auth('owner')
        fields = ('id', 'name', 'inventory', 'is_network', 'blacklist')
        validation = SetValidation()
        filtering = {'inventory': ALL}

    def dehydrate_targetvalues_ids(self, bundle):
        ids = []
        for pub_id in bundle.obj.target_values.values('id'):
            ids.append(pub_id['id'])

        return ids

    def dehydrate_targetvalues(self, bundle):
        if bundle.obj.is_network:
            return self._dehydrate_networks(bundle)

        return self._dehydrate_publishers(bundle)

    def _dehydrate_publishers(self, bundle):

        publishers = []

        for publisher in bundle.obj.targetvalues:
            publishers.append({
                'id':
                publisher.pk,
                'inventory':
                publisher.inventory,
                'name':
                publisher.name,
                'network':
                publisher.network,
                'publisher_id':
                '{0}-{1}'.format(publisher.network_id, publisher.publisher_id),
                'sizes':
                publisher.sizes,
                'positions':
                publisher.positions,
                'segments':
                publisher.segments
            })
        return publishers

    def _dehydrate_networks(self, bundle):

        networks = []

        for network in bundle.obj.targetvalues:
            network_dict = {
                'id': network.pk,
                'network': network.network,
                'network_id': network.network_id,
                'inventory': network.inventory
            }

            networks.append(network_dict)

        return networks

    def hydrate_m2m(self, bundle):
        if self.is_valid(bundle):
            target_values = TargetValue.objects.representants().filter(
                id__in=bundle.data.get('targetvalues_ids', []))
            bundle.obj.target_values = target_values

    def hydrate(self, bundle):
        bundle.obj.owner = bundle.request.user.account
        return bundle
Exemplo n.º 14
0
class CreativeResource(ProtectedModelResource):
    class Meta:
        resource_name = 'creative'
        allowed_methods = ('get', 'post', 'get', 'put', 'delete')
        always_return_data = True
        filtering = {
            'destination': (
                'exact',
                'startswith',
            ),
        }

        queryset = Creative.objects_visible.all()
        authorization = Auth('owner')
        fields = ('name', 'width', 'height', 'api_data', 'destination')
        validation = CreativeValidation()

    id = IntegerField('id', readonly=True)
    size = ListField('size', readonly=True)
    type = CharField(readonly=True)
    status = CharField('appnexus_status', readonly=True)
    api_data = CharField('api_data')
    vast_url = CharField('vast_url', readonly=True, null=True)
    to_audit = BooleanField('to_audit', readonly=True, null=True)

    fb_title = CharField('title', null=True)
    fb_body = CharField('body', null=True)
    fb_message = CharField('message', null=True)
    fb_domain = CharField('domain', null=True)
    fb_brand_page = IntegerField('brand_id', null=True)

    def prepend_urls(self):
        return [
            url(r"^{0}/audit/(?P<creative_id>[\d]+)$".format(
                self._meta.resource_name, ),
                self.wrap_view('manual_audit'),
                name="creative_manual_audit"),
        ]

    def manual_audit(self, request, creative_id, **kwargs):
        """
        Manual audit api view.

        :param request: request object
        :param int creative_id: creative which we want to send to audit

        Returns detail response.
        """
        creative = Creative.objects.get(id=creative_id)
        creative.to_audit = True
        creative.save()
        return self.get_detail(request, pk=creative_id)

    def dehydrate_destination(self, bundle):
        return bundle.obj.get_destination_display()

    def dehydrate(self, bundle):
        creative = bundle.obj
        # get type based on class name
        bundle.data['type'] = creative.type
        bundle.data['status'] = creative.state.status
        bundle.data['is_auditable'] = creative.is_auditable

        if creative.is_facebook_destination(verify_is_newsfeed=True):
            bundle.data[
                'fb_brand_page_access'] = creative.brand.appnexus_access_status

        if creative.type == 'Video':
            bundle.data['liverail_status'] = creative.liverail_status
        else:
            bundle.data['liverail_status'] = ''

        # If facebook creative was added to strategy,
        # Add information about strategy and campaign
        if creative.is_facebook_destination():
            # For facebook creatives there is only one advert
            advert = creative.advert_set.filter(
                is_deleted=False,
                strategy__is_deleted=False,
                strategy__campaign__is_deleted=False).first()
            if advert:
                strategy = advert.strategy
                campaign = strategy.campaign
                bundle.data['strategy'] = strategy.name
                bundle.data['campaign'] = campaign.name

        return bundle

    def hydrate_destination(self, bundle):
        bundle.data['destination'] = DESTINATION[bundle.data['destination']]
        return bundle

    def hydrate_fb_brand_page(self, bundle):
        """ Clear creative brand page if it is not facebook newsfeed. """
        if bundle.data['destination'] != 'facebook_newsfeed':
            bundle.data['fb_brand_page'] = None
        return bundle

    def hydrate(self, bundle):
        # A bug in Tastypie: on update, hydrate is called 2 times,
        # once with obj.id == None and method == 'PUT'
        # We should create an object only if method is POST
        if not bundle.obj.id and bundle.request.method == 'POST':
            bundle.obj = creative_factory(bundle.data['type'],
                                          owner=bundle.request.user.account)

        return bundle
Exemplo n.º 15
0
class PresentationMediumResource(FootprintResource):
    """
        The through class between Presentation and Medium, a list of which are loaded by a PresentationResource instance to give the user access to the corresponding Medium and also the important db_entity method, which returns the selected DbEntity interest of the PresentationMedium's db_entity_key
    """

    # The db_entity--We don't expose the DbEntityInterest to the client
    db_entity = fields.ToOneField(DbEntityResource,
                                  attribute='db_entity',
                                  null=False)
    # Return the full Medium
    medium = fields.ToOneField(MediumResource,
                               attribute='medium',
                               null=False,
                               full=True)
    # The configuration of items not directly related to the Medium, such as graph labels. These are usually also
    # editable by the user.
    configuration = PickledDictField(attribute='configuration',
                                     null=True,
                                     blank=True,
                                     default=lambda: {})

    visible_attributes = ListField(attribute='visible_attributes',
                                   null=True,
                                   blank=True)

    creator = fields.ToOneField(UserResource,
                                'creator',
                                full=True,
                                null=True,
                                readonly=True)
    updater = fields.ToOneField(UserResource,
                                'updater',
                                full=True,
                                null=True,
                                readonly=True)

    def dehydrate_medium_context(self, bundle):
        # Remove data that isn't needed by the API
        return remove_keys(['attributes'])

    def hydrate(self, bundle):
        """
            Set the user who created the Layer
        :param bundle:
        :return:
        """
        if not bundle.obj.id:
            bundle.obj.creator = self.resolve_user(bundle.request.GET)
        bundle.obj.updater = self.resolve_user(bundle.request.GET)
        return super(PresentationMediumResource, self).hydrate(bundle)

    def full_hydrate(self, bundle):
        super(PresentationMediumResource, self).full_hydrate(bundle)
        if not bundle.data.get(
                'id'
        ) and bundle.obj.db_entity_interest.db_entity.origin_instance:
            # If cloning, copy the medium_context.attributes
            config_entity = bundle.obj.db_entity_interest.config_entity
            origin_db_entity = bundle.obj.db_entity_interest.db_entity.origin_instance
            presentation_medium = PresentationMedium.objects.get(
                presentation__config_entity=config_entity,
                db_entity_key=origin_db_entity.key)
            bundle.data['medium']['attributes'] = presentation_medium.medium[
                'attributes']
        return bundle

    class Meta(FootprintResource.Meta):
        resource_name = 'presentation_medium'
        always_return_data = True
        queryset = PresentationMedium.objects.all()
        excludes = ['rendered_medium']
Exemplo n.º 16
0
class UploadedLayerResource(ModelResource):
    """
    API for accessing UploadedData.
    """

    geonode_layer = DictField(attribute='layer_data', readonly=True, null=True)
    configuration_options = DictField(attribute='configuration_options',
                                      null=True)
    fields = ListField(attribute='fields')
    status = CharField(attribute='status', readonly=True, null=True)

    class Meta:
        queryset = UploadLayer.objects.all()
        resource_name = 'data-layers'
        allowed_methods = ['get']
        filtering = {'id': ALL}
        authentication = SessionAuthentication()

    def get_object_list(self, request):
        """
        Filters the list view by the current user.
        """
        return super(
            UploadedLayerResource,
            self).get_object_list(request).filter(upload__user=request.user.id)

    def import_layer(self, request, **kwargs):
        """
        Imports a layer
        """
        self.method_check(request, allowed=['post'])

        b = Bundle()
        b.request = request

        try:
            obj = self.obj_get(b, pk=kwargs.get('pk'))
        except UploadLayer.DoesNotExist:
            raise ImmediateHttpResponse(response=http.HttpNotFound())

        configuration_options = request.POST.get('configurationOptions')

        if 'application/json' in request.META.get('CONTENT_TYPE', ''):
            configuration_options = json.loads(request.body)

        if isinstance(configuration_options, dict):
            obj.configuration_options = configuration_options
            obj.save()
            configuration_options = [configuration_options]

        if not configuration_options:
            raise ImmediateHttpResponse(
                response=http.HttpBadRequest('Configuration options missing.'))

        uploaded_file = obj.upload.uploadfile_set.first()
        import_result = import_object.delay(
            uploaded_file.id, configuration_options=configuration_options)

        # query the db again for this object since it may have been updated during the import
        obj = self.obj_get(b, pk=kwargs.get('pk'))
        obj.task_id = import_result.id
        obj.save()

        return self.create_response(request, {'task': obj.task_id})

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>{0})/(?P<pk>\w[\w/-]*)/configure{1}$".
                format(self._meta.resource_name, trailing_slash()),
                self.wrap_view('import_layer'),
                name="importer_configure"),
        ]
Exemplo n.º 17
0
    def dynamic_resource_subclass(self,
                                  layer_selection=None,
                                  db_entity=None,
                                  feature_class=None,
                                  config_entity=None,
                                  metadata=None,
                                  params=None,
                                  **kwargs):
        """
            Creates the dynamic Feature Resource class by passing in a layer_selection, db_entity, or feature_class
        :param layer_selection: Required if db_entity or metadata aren't present
        :param db_entity: Required if layer_selection or metadata aren't present
        :param metadata: Required along with config_entity if layer_selection or db_entity aren't present
        :param kwargs:
        :return:
        """
        feature_class_configuration = None
        if layer_selection:
            # Coming in relative to a LayerSelection, which puts us in the context of the LayerSelection's
            # feature query for this Feature subclass
            layer = layer_selection.layer
            # If we pass in a ConfigEntity it means we want to scope the Feature class to its scope.
            # The ConfigEntity defaults to that of the Layer, but we can override it to be a lower
            # scope to make sure that we have access to lower DbEntities of performing joins
            config_entity = config_entity.subclassed if config_entity else layer.config_entity.subclassed
            logger.debug(
                "Resolving FeatureResource subclass for layer_selection: {0}, config_entity: {1}"
                .format(layer_selection.unique_id, config_entity.id))
            # Resolve the dynamic Feature class with the given config_entity so that we can access all DbEntities
            # of the ConfigEntity for joins
            feature_class = config_entity.db_entity_feature_class(
                layer.db_entity.key)
        elif db_entity:
            # Coming in relative to a DbEntity, meaning we don't care about a particular LayerSelection's
            # feature query for this Feature subclass
            config_entity = db_entity.config_entity
            logger.debug(
                "Resolving FeatureResource subclass for db_entity: {0}, config_entity: {1}"
                .format(db_entity.id, config_entity.id))
            # Resolve the dynamic Feature class with the given config_entity so that we can access all DbEntities
            # of the ConfigEntity for joins
            feature_class = config_entity.db_entity_feature_class(
                db_entity.key)
        elif metadata:
            # Coming in with metadata, meaning this is and uploaded or ArcGis table with no DbEntity yet
            # We need to construct a FeatureClass from the metadata
            logger.debug(
                "Resolving FeatureResource subclass for metadata: {0}, config_entity: {1}"
                .format(metadata, config_entity.id))
            feature_class_creator = FeatureClassCreator(config_entity)
            feature_class_configuration = feature_class_creator.feature_class_configuration_from_metadata(
                metadata['schema'])
            feature_class = FeatureClassCreator(
                config_entity,
                feature_class_configuration).dynamic_model_class()

        if not feature_class_configuration:
            # If we didn't already ensure all dynamic model classes have been created
            # This only need to run once to get all dynamic feature subclasses into memory,
            # in case they are needed by an association, join, or something similar
            feature_class_creator = FeatureClassCreator.from_dynamic_model_class(
                feature_class)
            feature_class_creator.ensure_dynamic_models()

        logger.debug("Resolving resource for Feature subclass: {0}".format(
            feature_class))

        # Resolve the FeatureResource subclass based on the given Feature subclass
        # If self is already a subclass, just return self
        # Else, return a preconfigured subclass or one dynamically created. The latter will probably be the only way in the future.
        # If not already subclassed
        is_singleton_feature = issubclass(self.__class__,
                                          SingletonFeatureResourceMixin)
        is_template_feature = self.__class__ == TemplateFeatureResource
        if self.__class__ in [
                FeatureResource, TemplateFeatureResource,
                FeatureCategoryAttributeResource,
                FeatureQuantitativeAttributeResource
        ]:
            if is_singleton_feature or params.get('is_feature_attribute'):
                queryset = feature_class.objects.none()
            elif kwargs.get('method', None) == 'PATCH':
                # It's possible to PATCH with an active join query.
                # But we don't want to use a join query when patching
                queryset = feature_class.objects.all()
            else:
                # Get the queryset stored by the layer_selection or an empty query if we don't have a layer_selection
                queryset = layer_selection.selected_features_or_values if\
                    layer_selection else \
                    feature_class.objects.none()

                if layer_selection and not (is_singleton_feature or kwargs.get(
                        'query_may_be_empty')) and queryset.count() == 0:
                    raise Exception(
                        "Unexpected empty queryset for layer_selection features: %s"
                        % queryset.query)
            is_values_queryset = isinstance(queryset, ValuesQuerySet)

            #returns queryset ordered by the table id
            queryset = queryset.order_by('id')

            if is_values_queryset:
                join_feature_class = layer_selection.create_join_feature_class(
                ) if is_values_queryset else feature_class
                logger.info("Created join_feature_class: %s" %
                            join_feature_class)
                # Force the queryset to our new class so that Tastypie can map the dict results to it
                queryset.model = join_feature_class

                return self.__class__.resolve_resource_class(
                    join_feature_class,
                    queryset=queryset,
                    base_resource_class=self.join_feature_resource_class(
                        join_feature_class),
                    additional_fields_dict=dict(
                        # Pass these to the feature resource to help it resolve
                        # field mappings and add related fields (just need for join_feature_class)
                        # Use the layer_selection if it exists since it might have filtered or extra query fields
                        result_field_lookup=(layer_selection
                                             or db_entity).result_field_lookup
                        if not metadata else {},
                        related_field_lookup=(
                            layer_selection or db_entity).related_field_lookup
                        if not metadata else {},
                        # We use these in the FeatureResource to create a unique id for each join Feature
                        join_model_attributes=layer_selection
                        and layer_selection.result_map.join_model_attributes),
                    is_join_query=True,
                    limit_fields=layer_selection.result_map['result_fields'])
            else:
                abstract_feature_resource_class = self.__class__
                resource_class = abstract_feature_resource_class.resolve_resource_class(
                    feature_class,
                    queryset=queryset,
                    # Give FeatureResource a reference to the layer_selection
                    additional_fields_dict=merge(
                        dict(
                            # Pass this to the feature resource to help it resolve field mappings
                            result_field_lookup=(layer_selection or db_entity).
                            result_field_lookup if not metadata else {}),
                        dict(
                            # Not sure why it doesn't work to just stick this on the TemplateFeatureResource
                            feature_fields=ListField(
                                attribute='feature_fields',
                                null=True,
                                blank=True,
                                readonly=True),
                            feature_field_title_lookup=PickledDictField(
                                attribute='feature_field_title_lookup',
                                null=True,
                                blank=True,
                                readonly=True),
                        ) if is_template_feature else dict()),
                    for_template=is_template_feature)
                return resource_class
        return self