|
| 1 | +import debugpy |
| 2 | +import socket |
| 3 | +from django.core.management.commands.runserver import Command as RunServerCommand |
| 4 | + |
| 5 | + |
| 6 | +class Command(RunServerCommand): |
| 7 | + help = "Run the Django development server with debugpy for VS Code debugging" |
| 8 | + |
| 9 | + def add_arguments(self, parser): |
| 10 | + super().add_arguments(parser) |
| 11 | + parser.add_argument("--debug-port", type=int, default=5678, help="Port for the debug server (default: 5678)") |
| 12 | + parser.add_argument( |
| 13 | + "--wait-for-client", action="store_true", help="Wait for debugger client to attach before starting server" |
| 14 | + ) |
| 15 | + |
| 16 | + def is_port_in_use(self, port): |
| 17 | + """Check if a port is already in use""" |
| 18 | + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: |
| 19 | + try: |
| 20 | + s.bind(("0.0.0.0", port)) |
| 21 | + return False |
| 22 | + except OSError: |
| 23 | + return True |
| 24 | + |
| 25 | + def handle(self, *args, **options): |
| 26 | + debug_port = options.get("debug_port", 5678) |
| 27 | + wait_for_client = options.get("wait_for_client", False) |
| 28 | + |
| 29 | + # Check if debugpy is already initialized or connected |
| 30 | + if debugpy.is_client_connected(): |
| 31 | + self.stdout.write(self.style.WARNING(f"Debugger already connected on port {debug_port}")) |
| 32 | + else: |
| 33 | + # Check if debug port is in use |
| 34 | + if self.is_port_in_use(debug_port): |
| 35 | + self.stdout.write(self.style.ERROR(f"Port {debug_port} is already in use. Debug server not started.")) |
| 36 | + self.stdout.write(self.style.WARNING("Django server will start without debug capability.")) |
| 37 | + else: |
| 38 | + try: |
| 39 | + # Only configure debugpy if not already configured |
| 40 | + if not hasattr(debugpy, "_is_configured") or not debugpy._is_configured: |
| 41 | + # Listen for debugger connections |
| 42 | + debugpy.listen(("0.0.0.0", debug_port)) |
| 43 | + self.stdout.write(self.style.SUCCESS(f"Debug server listening on port {debug_port}")) |
| 44 | + |
| 45 | + if wait_for_client: |
| 46 | + self.stdout.write(self.style.WARNING("Waiting for debugger client to attach...")) |
| 47 | + debugpy.wait_for_client() |
| 48 | + self.stdout.write(self.style.SUCCESS("Debugger client attached!")) |
| 49 | + else: |
| 50 | + self.stdout.write(self.style.SUCCESS("Server starting - you can now attach the debugger")) |
| 51 | + else: |
| 52 | + self.stdout.write(self.style.WARNING("Debug server already configured")) |
| 53 | + |
| 54 | + except Exception as e: |
| 55 | + self.stdout.write(self.style.ERROR(f"Failed to start debug server: {str(e)}")) |
| 56 | + self.stdout.write(self.style.WARNING("Django server will start without debug capability.")) |
| 57 | + |
| 58 | + # Call the parent runserver command |
| 59 | + super().handle(*args, **options) |
0 commit comments