12345678910111213141516171819202122232425262728293031323334353637383940 |
- from django.dispatch import receiver
- from django.db.models.signals import post_save, post_delete
- from .models import Service, IPPrefix, IPResource, Switch, Port
- from ipaddress import ip_address, ip_network
- @receiver(post_save, sender=IPPrefix, dispatch_uid='ip_prefix')
- def ip_prefix(sender, instance, created, **kwargs):
- network = ip_network(instance.prefix)
- for ip in IPResource.objects.all():
- address = ip_address(ip.ip)
- if address in network:
- ip.prefixes.add(instance)
- else:
- ip.prefixes.remove(instance)
- @receiver(post_save, sender=IPResource, dispatch_uid='ip_resource')
- def ip_resource(sender, instance, created, **kwargs):
- address = ip_address(instance.ip)
- for prefix in IPPrefix.objects.all():
- network = ip_network(prefix.prefix)
- if address in network:
- instance.prefixes.add(prefix)
- else:
- instance.prefixes.remove(prefix)
- @receiver(post_delete, sender=Service, dispatch_uid='delete_service_contribution')
- def delete_service_contribution(sender, instance, **kwargs):
- instance.contribution.delete()
- @receiver(post_save, sender=Switch, dispatch_uid='create_switch_ports')
- def create_switch_ports(sender, instance, created, **kwargs):
- if created:
- ports = [ Port(switch=instance, port=i) for i in range(instance.first_port, instance.last_port + 1) ]
- Port.objects.bulk_create(ports)
|