Skip to content

Commit

Permalink
Cleanup for #9102
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremystretch committed Jul 7, 2022
1 parent 1beb852 commit 9a7f3f8
Show file tree
Hide file tree
Showing 17 changed files with 168 additions and 169 deletions.
3 changes: 2 additions & 1 deletion netbox/circuits/graphql/types.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from circuits import filtersets, models
from dcim.graphql.mixins import CabledObjectMixin
from extras.graphql.mixins import CustomFieldsMixin, TagsMixin
from netbox.graphql.types import ObjectType, OrganizationalObjectType, NetBoxObjectType

Expand All @@ -11,7 +12,7 @@
)


class CircuitTerminationType(CustomFieldsMixin, TagsMixin, ObjectType):
class CircuitTerminationType(CustomFieldsMixin, TagsMixin, CabledObjectMixin, ObjectType):

class Meta:
model = models.CircuitTermination
Expand Down
35 changes: 15 additions & 20 deletions netbox/dcim/api/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,13 @@ def get_link_peers(self, obj):
"""
Return the appropriate serializer for the link termination model.
"""
if not obj.cable:
if not obj.link_peers:
return []

# Return serialized peer termination objects
if obj.link_peers:
serializer = get_serializer_for_model(obj.link_peers[0], prefix='Nested')
context = {'request': self.context['request']}
return serializer(obj.link_peers, context=context, many=True).data

return []
serializer = get_serializer_for_model(obj.link_peers[0], prefix='Nested')
context = {'request': self.context['request']}
return serializer(obj.link_peers, context=context, many=True).data

@swagger_serializer_method(serializer_or_field=serializers.BooleanField)
def get__occupied(self, obj):
Expand All @@ -77,17 +74,15 @@ class ConnectedEndpointsSerializer(serializers.ModelSerializer):
connected_endpoints_reachable = serializers.SerializerMethodField(read_only=True)

def get_connected_endpoints_type(self, obj):
endpoints = obj.connected_endpoints
if endpoints:
if endpoints := obj.connected_endpoints:
return f'{endpoints[0]._meta.app_label}.{endpoints[0]._meta.model_name}'

@swagger_serializer_method(serializer_or_field=serializers.ListField)
def get_connected_endpoints(self, obj):
"""
Return the appropriate serializer for the type of connected object.
"""
endpoints = obj.connected_endpoints
if endpoints:
if endpoints := obj.connected_endpoints:
serializer = get_serializer_for_model(endpoints[0], prefix='Nested')
context = {'request': self.context['request']}
return serializer(endpoints, many=True, context=context).data
Expand Down Expand Up @@ -1016,15 +1011,15 @@ class Meta:
]

def _get_terminations_type(self, obj, side):
assert side.lower() in ('a', 'b')
terms = [t.termination for t in obj.terminations.all() if t.cable_end == side.upper()]
assert side in CableEndChoices.values()
terms = getattr(obj, f'get_{side.lower()}_terminations')()
if terms:
ct = ContentType.objects.get_for_model(terms[0])
return f"{ct.app_label}.{ct.model}"

def _get_terminations(self, obj, side):
assert side.lower() in ('a', 'b')
terms = [t.termination for t in obj.terminations.all() if t.cable_end == side.upper()]
assert side in CableEndChoices.values()
terms = getattr(obj, f'get_{side.lower()}_terminations')()
if not terms:
return []

Expand All @@ -1037,19 +1032,19 @@ def _get_terminations(self, obj, side):

@swagger_serializer_method(serializer_or_field=serializers.CharField)
def get_a_terminations_type(self, obj):
return self._get_terminations_type(obj, 'a')
return self._get_terminations_type(obj, CableEndChoices.SIDE_A)

@swagger_serializer_method(serializer_or_field=serializers.CharField)
def get_b_terminations_type(self, obj):
return self._get_terminations_type(obj, 'b')
return self._get_terminations_type(obj, CableEndChoices.SIDE_B)

@swagger_serializer_method(serializer_or_field=serializers.DictField)
def get_a_terminations(self, obj):
return self._get_terminations(obj, 'a')
return self._get_terminations(obj, CableEndChoices.SIDE_A)

@swagger_serializer_method(serializer_or_field=serializers.DictField)
def get_b_terminations(self, obj):
return self._get_terminations(obj, 'b')
return self._get_terminations(obj, CableEndChoices.SIDE_B)


class TracedCableSerializer(serializers.ModelSerializer):
Expand All @@ -1066,7 +1061,7 @@ class Meta:


class CableTerminationSerializer(NetBoxModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name='dcim-api:cable-detail')
url = serializers.HyperlinkedIdentityField(view_name='dcim-api:cabletermination-detail')
termination_type = ContentTypeField(
queryset=ContentType.objects.filter(CABLE_TERMINATION_MODELS)
)
Expand Down
32 changes: 13 additions & 19 deletions netbox/dcim/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from dcim import filtersets
from dcim.constants import CABLE_TRACE_SVG_DEFAULT_WIDTH
from dcim.models import *
from dcim.svg import CableTraceSVG
from extras.api.views import ConfigContextQuerySetMixin
from ipam.models import Prefix, VLAN
from netbox.api.authentication import IsAuthenticatedOrLoginNotRequired
Expand Down Expand Up @@ -52,37 +53,30 @@ def trace(self, request, pk):
# Initialize the path array
path = []

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

# Serialize path objects, iterating over each three-tuple in the path
for near_end, cable, far_end in obj.trace():
if near_end is None:
# Split paths
if near_end is not None:
serializer_a = get_serializer_for_model(near_end[0], prefix='Nested')
near_end = serializer_a(near_end, many=True, context={'request': request}).data
else:
# Path is split; stop here
break

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

path.append((x, y, z))
path.append((near_end, cable, far_end))

return Response(path)

Expand Down
2 changes: 1 addition & 1 deletion netbox/dcim/choices.py
Original file line number Diff line number Diff line change
Expand Up @@ -1294,7 +1294,7 @@ class CableEndChoices(ChoiceSet):
CHOICES = (
(SIDE_A, 'A'),
(SIDE_B, 'B'),
('', ''),
# ('', ''),
)


Expand Down
5 changes: 5 additions & 0 deletions netbox/dcim/graphql/mixins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class CabledObjectMixin:

def resolve_cable_end(self, info):
# Handle empty values
return self.cable_end or None
17 changes: 9 additions & 8 deletions netbox/dcim/graphql/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from ipam.graphql.mixins import IPAddressesMixin, VLANGroupsMixin
from netbox.graphql.scalars import BigInt
from netbox.graphql.types import BaseObjectType, OrganizationalObjectType, NetBoxObjectType
from .mixins import CabledObjectMixin

__all__ = (
'CableType',
Expand Down Expand Up @@ -107,7 +108,7 @@ class Meta:
filterset_class = filtersets.CableTerminationFilterSet


class ConsolePortType(ComponentObjectType):
class ConsolePortType(ComponentObjectType, CabledObjectMixin):

class Meta:
model = models.ConsolePort
Expand All @@ -129,7 +130,7 @@ def resolve_type(self, info):
return self.type or None


class ConsoleServerPortType(ComponentObjectType):
class ConsoleServerPortType(ComponentObjectType, CabledObjectMixin):

class Meta:
model = models.ConsoleServerPort
Expand Down Expand Up @@ -211,7 +212,7 @@ def resolve_airflow(self, info):
return self.airflow or None


class FrontPortType(ComponentObjectType):
class FrontPortType(ComponentObjectType, CabledObjectMixin):

class Meta:
model = models.FrontPort
Expand All @@ -227,7 +228,7 @@ class Meta:
filterset_class = filtersets.FrontPortTemplateFilterSet


class InterfaceType(IPAddressesMixin, ComponentObjectType):
class InterfaceType(IPAddressesMixin, ComponentObjectType, CabledObjectMixin):

class Meta:
model = models.Interface
Expand Down Expand Up @@ -330,15 +331,15 @@ class Meta:
filterset_class = filtersets.PlatformFilterSet


class PowerFeedType(NetBoxObjectType):
class PowerFeedType(NetBoxObjectType, CabledObjectMixin):

class Meta:
model = models.PowerFeed
exclude = ('_path',)
filterset_class = filtersets.PowerFeedFilterSet


class PowerOutletType(ComponentObjectType):
class PowerOutletType(ComponentObjectType, CabledObjectMixin):

class Meta:
model = models.PowerOutlet
Expand Down Expand Up @@ -374,7 +375,7 @@ class Meta:
filterset_class = filtersets.PowerPanelFilterSet


class PowerPortType(ComponentObjectType):
class PowerPortType(ComponentObjectType, CabledObjectMixin):

class Meta:
model = models.PowerPort
Expand Down Expand Up @@ -426,7 +427,7 @@ class Meta:
filterset_class = filtersets.RackRoleFilterSet


class RearPortType(ComponentObjectType):
class RearPortType(ComponentObjectType, CabledObjectMixin):

class Meta:
model = models.RearPort
Expand Down
2 changes: 1 addition & 1 deletion netbox/dcim/migrations/0157_new_cabling_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class Migration(migrations.Migration):
),
migrations.AddConstraint(
model_name='cabletermination',
constraint=models.UniqueConstraint(fields=('termination_type', 'termination_id'), name='unique_termination'),
constraint=models.UniqueConstraint(fields=('termination_type', 'termination_id'), name='dcim_cable_termination_unique_termination'),
),

# Update CablePath model
Expand Down
Loading

0 comments on commit 9a7f3f8

Please sign in to comment.