Exemplo n.º 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, pk=pk)

        # Initialize the path array
        path = []

        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)
Exemplo n.º 2
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
Exemplo n.º 3
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
Exemplo n.º 4
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
Exemplo n.º 5
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
Exemplo n.º 6
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
Exemplo n.º 7
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
Exemplo n.º 8
0
    def members(self, request, pk, *args, **kwargs):
        """List member objects of the same type as the `content_type` for this dynamic group."""
        instance = get_object_or_404(self.queryset, pk=pk)

        # Retrieve the serializer for the content_type and paginate the results
        member_model_class = instance.content_type.model_class()
        member_serializer_class = get_serializer_for_model(member_model_class)
        members = self.paginate_queryset(instance.members)
        member_serializer = member_serializer_class(members, many=True, context={"request": request})
        return self.get_paginated_response(member_serializer.data)
Exemplo n.º 9
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
Exemplo n.º 10
0
    def get_serializer_class(self):
        logger = logging.getLogger("nautobot.core.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
        return self.serializer_class
Exemplo n.º 11
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
Exemplo n.º 12
0
def serialize_object_v2(obj):
    """
    Return a JSON serialized representation of an object using obj's serializer.
    """
    from nautobot.core.api.exceptions import SerializerNotFound
    from nautobot.utilities.api import get_serializer_for_model

    # Try serializing obj(model instance) using its API Serializer
    try:
        serializer_class = get_serializer_for_model(obj.__class__)
        data = serializer_class(obj, context={"request": None}).data
    except SerializerNotFound:
        # Fall back to generic JSON representation of obj
        data = serialize_object(obj)

    return data
Exemplo n.º 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)

        # Enqueue the webhooks
        for webhook in webhooks:
            args = [
                webhook.pk,
                serializer.data,
                instance._meta.model_name,
                action,
                str(timezone.now()),
                user.username,
                request_id,
            ]
            process_webhook.apply_async(args=args)
Exemplo n.º 14
0
 def get_owner(self, obj):
     if obj.owner is None:
         return None
     serializer = get_serializer_for_model(obj.owner, prefix="Nested")
     context = {"request": self.context["request"]}
     return serializer(obj.owner, context=context).data