示例#1
0
    def trace(self, request, pk):
        """
        Trace a complete cable path and return each segment as a three-tuple of (termination, cable, termination).
        """
        obj = get_object_or_404(self.queryset.model, pk=pk)

        # Initialize the path array
        path = []

        for near_end, cable, far_end in obj.trace(follow_circuits=True):

            # Serialize each object
            serializer_a = get_serializer_for_model(near_end, prefix='Nested')
            x = serializer_a(near_end, context={'request': request}).data
            if cable is not None:
                y = serializers.TracedCableSerializer(cable,
                                                      context={
                                                          'request': request
                                                      }).data
            else:
                y = None
            if far_end is not None:
                serializer_b = get_serializer_for_model(far_end,
                                                        prefix='Nested')
                z = serializer_b(far_end, context={'request': request}).data
            else:
                z = None

            path.append((x, y, z))

        return Response(path)
示例#2
0
    def trace(self, request, pk):
        """
        Trace a complete cable path and return each segment as a three-tuple of (termination, cable, termination).
        """
        obj = get_object_or_404(self.queryset.model, pk=pk)

        # Initialize the path array
        path = []

        for near_end, cable, far_end in obj.trace(follow_circuits=True):

            # Serialize each object
            serializer_a = get_serializer_for_model(near_end, prefix='Nested')
            x = serializer_a(near_end, context={'request': request}).data
            if cable is not None:
                y = serializers.TracedCableSerializer(cable, context={'request': request}).data
            else:
                y = None
            if far_end is not None:
                serializer_b = get_serializer_for_model(far_end, prefix='Nested')
                z = serializer_b(far_end, context={'request': request}).data
            else:
                z = None

            path.append((x, y, z))

        return Response(path)
示例#3
0
 def get_path(self, obj):
     ret = []
     for node in obj.get_path():
         serializer = get_serializer_for_model(node, prefix='Nested')
         context = {'request': self.context['request']}
         ret.append(serializer(node, context=context).data)
     return ret
示例#4
0
 def get_origin(self, obj):
     """
     Return the appropriate serializer for the origin.
     """
     serializer = get_serializer_for_model(obj.origin, prefix='Nested')
     context = {'request': self.context['request']}
     return serializer(obj.origin, context=context).data
示例#5
0
    def get_scope(self, obj):
        if obj.scope_id is None:
            return None
        serializer = get_serializer_for_model(obj.scope, prefix='Nested')
        context = {'request': self.context['request']}

        return serializer(obj.scope, context=context).data
示例#6
0
 def get_assigned_object(self, obj):
     if obj.assigned_object is None:
         return None
     serializer = get_serializer_for_model(obj.assigned_object,
                                           prefix='Nested')
     context = {'request': self.context['request']}
     return serializer(obj.assigned_object, context=context).data
示例#7
0
    def trace(self, request, pk):
        """
        Trace a complete cable path and return each segment as a three-tuple of (termination, cable, termination).
        """
        obj = get_object_or_404(self.queryset, pk=pk)

        # Initialize the path array
        path = []

        if request.GET.get('render', None) == 'svg':
            # Render SVG
            try:
                width = min(int(request.GET.get('width')), 1600)
            except (ValueError, TypeError):
                width = None
            drawing = obj.get_trace_svg(
                base_url=request.build_absolute_uri('/'), width=width)
            return HttpResponse(drawing.tostring(),
                                content_type='image/svg+xml')

        for near_end, cable, far_end in obj.trace():
            if near_end is None:
                # Split paths
                break

            # Serialize each object
            serializer_a = get_serializer_for_model(near_end, prefix='Nested')
            x = serializer_a(near_end, context={'request': request}).data
            if cable is not None:
                y = serializers.TracedCableSerializer(cable,
                                                      context={
                                                          'request': request
                                                      }).data
            else:
                y = None
            if far_end is not None:
                serializer_b = get_serializer_for_model(far_end,
                                                        prefix='Nested')
                z = serializer_b(far_end, context={'request': request}).data
            else:
                z = None

            path.append((x, y, z))

        return Response(path)
示例#8
0
 def get_cable_peer(self, obj):
     """
     Return the appropriate serializer for the cable termination model.
     """
     if obj._cable_peer is not None:
         serializer = get_serializer_for_model(obj._cable_peer, prefix='Nested')
         context = {'request': self.context['request']}
         return serializer(obj._cable_peer, context=context).data
     return None
示例#9
0
 def get_destination(self, obj):
     """
     Return the appropriate serializer for the destination, if any.
     """
     if obj.destination_id is not None:
         serializer = get_serializer_for_model(obj.destination, prefix='Nested')
         context = {'request': self.context['request']}
         return serializer(obj.destination, context=context).data
     return None
示例#10
0
 def get_connected_endpoint(self, obj):
     """
     Return the appropriate serializer for the type of connected object.
     """
     if obj._path is not None and obj._path.destination is not None:
         serializer = get_serializer_for_model(obj._path.destination, prefix='Nested')
         context = {'request': self.context['request']}
         return serializer(obj._path.destination, context=context).data
     return None
示例#11
0
def serialize_for_webhook(instance):
    """
    Return a serialized representation of the given instance suitable for use in a webhook.
    """
    serializer_class = get_serializer_for_model(instance.__class__)
    serializer_context = {
        'request': None,
    }
    serializer = serializer_class(instance, context=serializer_context)

    return serializer.data
示例#12
0
    def get_connected_endpoint(self, obj):
        """
        Return the appropriate serializer for the type of connected object.
        """
        if getattr(obj, 'connected_endpoint', None) is None:
            return None

        serializer = get_serializer_for_model(obj.connected_endpoint, prefix='Nested')
        context = {'request': self.context['request']}
        data = serializer(obj.connected_endpoint, context=context).data

        return data
示例#13
0
def enqueue_webhooks(instance, user, request_id, action):
    """
    Find Webhook(s) assigned to this instance + action and enqueue them
    to be processed
    """
    # Determine whether this type of object supports webhooks
    app_label = instance._meta.app_label
    model_name = instance._meta.model_name
    if model_name not in registry['model_features']['webhooks'].get(
            app_label, []):
        return

    # Retrieve any applicable Webhooks
    content_type = ContentType.objects.get_for_model(instance)
    action_flag = {
        ObjectChangeActionChoices.ACTION_CREATE: 'type_create',
        ObjectChangeActionChoices.ACTION_UPDATE: 'type_update',
        ObjectChangeActionChoices.ACTION_DELETE: 'type_delete',
    }[action]
    webhooks = Webhook.objects.filter(content_types=content_type,
                                      enabled=True,
                                      **{action_flag: True})

    if webhooks.exists():

        # Get the Model's API serializer class and serialize the object
        serializer_class = get_serializer_for_model(instance.__class__)
        serializer_context = {
            'request': None,
        }
        serializer = serializer_class(instance, context=serializer_context)

        # Gather pre- and post-change snapshots
        snapshots = {
            'prechange':
            getattr(instance, '_prechange_snapshot', None),
            'postchange':
            serialize_object(instance)
            if action != ObjectChangeActionChoices.ACTION_DELETE else None,
        }

        # Enqueue the webhooks
        webhook_queue = get_queue('default')
        for webhook in webhooks:
            webhook_queue.enqueue("extras.webhooks_worker.process_webhook",
                                  webhook=webhook,
                                  model_name=instance._meta.model_name,
                                  event=action,
                                  data=serializer.data,
                                  snapshots=snapshots,
                                  timestamp=str(timezone.now()),
                                  username=user.username,
                                  request_id=request_id)
示例#14
0
    def get_connected_endpoint(self, obj):
        """
        Return the appropriate serializer for the type of connected object.
        """
        if getattr(obj, 'connected_endpoint', None) is None:
            return None

        serializer = get_serializer_for_model(obj.connected_endpoint, prefix='Nested')
        context = {'request': self.context['request']}
        data = serializer(obj.connected_endpoint, context=context).data

        return data
示例#15
0
 def get_changed_object(self, obj):
     """
     Serialize a nested representation of the changed object.
     """
     if obj.changed_object is None:
         return None
     serializer = get_serializer_for_model(obj.changed_object,
                                           prefix='Nested')
     if serializer is None:
         return obj.object_repr
     context = {'request': self.context['request']}
     data = serializer(obj.changed_object, context=context).data
     return data
示例#16
0
    def _get_termination(self, obj, side):
        """
        Serialize a nested representation of a termination.
        """
        if side.lower() not in ['a', 'b']:
            raise ValueError("Termination side must be either A or B.")
        termination = getattr(obj, 'termination_{}'.format(side.lower()))
        if termination is None:
            return None
        serializer = get_serializer_for_model(termination, prefix='Nested')
        context = {'request': self.context['request']}
        data = serializer(termination, context=context).data

        return data
示例#17
0
    def _get_termination(self, obj, side):
        """
        Serialize a nested representation of a termination.
        """
        if side.lower() not in ['a', 'b']:
            raise ValueError("Termination side must be either A or B.")
        termination = getattr(obj, 'termination_{}'.format(side.lower()))
        if termination is None:
            return None
        serializer = get_serializer_for_model(termination, prefix='Nested')
        context = {'request': self.context['request']}
        data = serializer(termination, context=context).data

        return data
示例#18
0
    def get_serializer_class(self):
        logger = logging.getLogger('netbox.api.views.ModelViewSet')

        # If using 'brief' mode, find and return the nested serializer for this model, if one exists
        if self.brief:
            logger.debug("Request is for 'brief' format; initializing nested serializer")
            try:
                serializer = get_serializer_for_model(self.queryset.model, prefix='Nested')
                logger.debug(f"Using serializer {serializer}")
                return serializer
            except SerializerNotFound:
                logger.debug(f"Nested serializer for {self.queryset.model} not found!")

        # Fall back to the hard-coded serializer class
        logger.debug(f"Using serializer {self.serializer_class}")
        return self.serializer_class
示例#19
0
    def get_changed_object(self, obj):
        """
        Serialize a nested representation of the changed object.
        """
        if obj.changed_object is None:
            return None

        try:
            serializer = get_serializer_for_model(obj.changed_object, prefix='Nested')
        except SerializerNotFound:
            return obj.object_repr
        context = {
            'request': self.context['request']
        }
        data = serializer(obj.changed_object, context=context).data

        return data
示例#20
0
def enqueue_webhooks(instance, user, request_id, action):
    """
    Find Webhook(s) assigned to this instance + action and enqueue them
    to be processed
    """
    obj_type = ContentType.objects.get_for_model(instance.__class__)

    webhook_models = ContentType.objects.filter(WEBHOOK_MODELS)
    if obj_type not in webhook_models:
        return

    # Retrieve any applicable Webhooks
    action_flag = {
        ObjectChangeActionChoices.ACTION_CREATE: 'type_create',
        ObjectChangeActionChoices.ACTION_UPDATE: 'type_update',
        ObjectChangeActionChoices.ACTION_DELETE: 'type_delete',
    }[action]
    webhooks = Webhook.objects.filter(obj_type=obj_type, enabled=True, **{action_flag: True})

    if webhooks.exists():
        # Get the Model's API serializer class and serialize the object
        serializer_class = get_serializer_for_model(instance.__class__)
        serializer_context = {
            'request': None,
        }
        serializer = serializer_class(instance, context=serializer_context)

        # We must only import django_rq if the Webhooks feature is enabled.
        # Only if we have gotten to ths point, is the feature enabled
        from django_rq import get_queue
        webhook_queue = get_queue('default')

        # enqueue the webhooks:
        for webhook in webhooks:
            webhook_queue.enqueue(
                "extras.webhooks_worker.process_webhook",
                webhook,
                serializer.data,
                instance._meta.model_name,
                action,
                str(datetime.datetime.now()),
                user.username,
                request_id
            )
示例#21
0
def enqueue_webhooks(instance, user, request_id, action):
    """
    Find Webhook(s) assigned to this instance + action and enqueue them
    to be processed
    """
    if not settings.WEBHOOKS_ENABLED or instance._meta.model_name not in WEBHOOK_MODELS:
        return

    # Retrieve any applicable Webhooks
    action_flag = {
        OBJECTCHANGE_ACTION_CREATE: 'type_create',
        OBJECTCHANGE_ACTION_UPDATE: 'type_update',
        OBJECTCHANGE_ACTION_DELETE: 'type_delete',
    }[action]
    obj_type = ContentType.objects.get_for_model(instance.__class__)
    webhooks = Webhook.objects.filter(obj_type=obj_type, enabled=True, **{action_flag: True})

    if webhooks.exists():
        # Get the Model's API serializer class and serialize the object
        serializer_class = get_serializer_for_model(instance.__class__)
        serializer_context = {
            'request': None,
        }
        serializer = serializer_class(instance, context=serializer_context)

        # We must only import django_rq if the Webhooks feature is enabled.
        # Only if we have gotten to ths point, is the feature enabled
        from django_rq import get_queue
        webhook_queue = get_queue('default')

        # enqueue the webhooks:
        for webhook in webhooks:
            webhook_queue.enqueue(
                "extras.webhooks_worker.process_webhook",
                webhook,
                serializer.data,
                instance._meta.model_name,
                action,
                str(datetime.datetime.now()),
                user.username,
                request_id
            )
示例#22
0
    def get_serializer_class(self):
        logger = logging.getLogger('netbox.api.views.ModelViewSet')

        # If 'brief' has been passed as a query param, find and return the nested serializer for this model, if one
        # exists
        request = self.get_serializer_context()['request']
        if request.query_params.get('brief'):
            logger.debug(
                "Request is for 'brief' format; initializing nested serializer"
            )
            try:
                serializer = get_serializer_for_model(self.queryset.model,
                                                      prefix='Nested')
                logger.debug(f"Using serializer {serializer}")
                return serializer
            except SerializerNotFound:
                pass

        # Fall back to the hard-coded serializer class
        logger.debug(f"Using serializer {self.serializer_class}")
        return self.serializer_class
示例#23
0
def enqueue_webhooks(instance, user, request_id, action):
    """
    Find Webhook(s) assigned to this instance + action and enqueue them
    to be processed
    """
    obj_type = ContentType.objects.get_for_model(instance.__class__)

    webhook_models = ContentType.objects.filter(FeatureQuery('webhooks').get_query())
    if obj_type not in webhook_models:
        return

    # Retrieve any applicable Webhooks
    action_flag = {
        ObjectChangeActionChoices.ACTION_CREATE: 'type_create',
        ObjectChangeActionChoices.ACTION_UPDATE: 'type_update',
        ObjectChangeActionChoices.ACTION_DELETE: 'type_delete',
    }[action]
    webhooks = Webhook.objects.filter(obj_type=obj_type, enabled=True, **{action_flag: True})

    if webhooks.exists():
        # Get the Model's API serializer class and serialize the object
        serializer_class = get_serializer_for_model(instance.__class__)
        serializer_context = {
            'request': None,
        }
        serializer = serializer_class(instance, context=serializer_context)

        # Enqueue the webhooks
        webhook_queue = get_queue('default')
        for webhook in webhooks:
            webhook_queue.enqueue(
                "extras.webhooks_worker.process_webhook",
                webhook,
                serializer.data,
                instance._meta.model_name,
                action,
                str(timezone.now()),
                user.username,
                request_id
            )
示例#24
0
    def serialize(self, instance, prefix=''):
        if not instance.pk:
            return None

        try:
            sender = instance.__class__
            record = sender.objects.get(pk=instance.pk)
        except Exception:
            record = instance

        try:
            fn = get_serializer_for_model(record, prefix)

            model = fn(record, context={'request': self.request})
            model = model.data

            # Prevent dictdiffer from trying to recurse infinitely.
            if 'tags' in model:
                model['tags'] = list(model['tags'])

            return model
        except Exception:
            return None
示例#25
0
文件: webhooks.py 项目: xonacs/netbox
def enqueue_webhooks(instance, action):
    """
    Find Webhook(s) assigned to this instance + action and enqueue them
    to be processed
    """
    if not settings.WEBHOOKS_ENABLED or instance._meta.model_name not in WEBHOOK_MODELS:
        return

    type_create = action == OBJECTCHANGE_ACTION_CREATE
    type_update = action == OBJECTCHANGE_ACTION_UPDATE
    type_delete = action == OBJECTCHANGE_ACTION_DELETE

    # Find assigned webhooks
    obj_type = ContentType.objects.get_for_model(instance.__class__)
    webhooks = Webhook.objects.filter(
        Q(enabled=True)
        & (Q(type_create=type_create) | Q(type_update=type_update)
           | Q(type_delete=type_delete)) & Q(obj_type=obj_type))

    if webhooks:
        # Get the Model's API serializer class and serialize the object
        serializer_class = get_serializer_for_model(instance.__class__)
        serializer_context = {
            'request': None,
        }
        serializer = serializer_class(instance, context=serializer_context)

        # We must only import django_rq if the Webhooks feature is enabled.
        # Only if we have gotten to ths point, is the feature enabled
        from django_rq import get_queue
        webhook_queue = get_queue('default')

        # enqueue the webhooks:
        for webhook in webhooks:
            webhook_queue.enqueue("extras.webhooks_worker.process_webhook",
                                  webhook, serializer.data, instance.__class__,
                                  action, str(datetime.datetime.now()))
示例#26
0
 def get_parent(self, obj):
     serializer = get_serializer_for_model(obj.parent, prefix='Nested')
     return serializer(obj.parent, context={'request': self.context['request']}).data
示例#27
0
 def get_assigned_object(self, instance):
     serializer = get_serializer_for_model(
         instance.assigned_object_type.model_class(), prefix='Nested')
     context = {'request': self.context['request']}
     return serializer(instance.assigned_object, context=context).data
def serializer(sender, prefix=''):
    try:
        return get_serializer_for_model(sender, prefix)
    except:
        return None