signals.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from django.dispatch import receiver
  2. from django.db.models.signals import post_save, post_delete
  3. from .models import Service, IPPrefix, IPResource, Switch, Port
  4. from ipaddress import ip_address, ip_network
  5. @receiver(post_save, sender=IPPrefix, dispatch_uid='ip_prefix')
  6. def ip_prefix(sender, instance, created, **kwargs):
  7. network = ip_network(instance.prefix)
  8. for ip in IPResource.objects.all():
  9. address = ip_address(ip.ip)
  10. if address in network:
  11. ip.prefixes.add(instance)
  12. else:
  13. ip.prefixes.remove(instance)
  14. @receiver(post_save, sender=IPResource, dispatch_uid='ip_resource')
  15. def ip_resource(sender, instance, created, **kwargs):
  16. address = ip_address(instance.ip)
  17. for prefix in IPPrefix.objects.all():
  18. network = ip_network(prefix.prefix)
  19. if address in network:
  20. instance.prefixes.add(prefix)
  21. else:
  22. instance.prefixes.remove(prefix)
  23. @receiver(post_delete, sender=Service, dispatch_uid='delete_service_contribution')
  24. def delete_service_contribution(sender, instance, **kwargs):
  25. instance.contribution.delete()
  26. @receiver(post_save, sender=Switch, dispatch_uid='create_switch_ports')
  27. def create_switch_ports(sender, instance, created, **kwargs):
  28. if created:
  29. ports = [ Port(switch=instance, port=i) for i in range(instance.first_port, instance.last_port + 1) ]
  30. Port.objects.bulk_create(ports)