4

I'm writing a web based code editor for Django projects. From within the editor I want to start the Django runserver command without it interfering with the server for the editor itself. Below is the code I use. The server (port 9999) is started but when I make a change to the code for the project whose server I just started both servers stop. The error is "That port is already in use"

def runserver(request, project_slug):
    project = Project.objects.get(slug=project_slug)
    import os
    os.system('cd %s; pwd; env; DJANGO_SETTINGS_MODULE=%s.settings; rm nohup.out; nohup python manage.py runserver 0.0.0.0:9999 &' % (project.get_current_directory(), project.slug))
    return HttpResponseRedirect(request.META['HTTP_REFERER'])   
Timothy Clemans
  • 1,711
  • 3
  • 16
  • 26

1 Answers1

2

You'll need to invest some more work into managing the server you start. If you call runserver(request, project_slug) more than once, that resource is going to be already taken up by another background process that is bound to that port and right now you don't even have a PID file to reference the process.

You'll need to add some gymnastics for starting/killing a WSGIServer and you'll definitely need to use the socket low-level networking library to have it select a free port for you--defer from selecting a port manually because you cannot guarantee that another processes on your system won't occupy the port and cause your application to get into an unrecoverable erroneous state.

Fortunately, though, you have the open source Lettuce project that properly manages a Django server instance in the background on a separate thread. Here's the actual code for the server, which I encourage you to see and adopt for your own purposes.

Community
  • 1
  • 1
Filip Dupanović
  • 32,650
  • 13
  • 84
  • 114