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)
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)
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
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
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
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
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)
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
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
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
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
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
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)
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
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
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
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
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
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
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 )
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 )
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
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 )
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
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()))
def get_parent(self, obj): serializer = get_serializer_for_model(obj.parent, prefix='Nested') return serializer(obj.parent, context={'request': self.context['request']}).data
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