How to restart a Django development web server in virtual machine on file modification?

803 views Asked by At

I have a VirtualBox machine managed by Vagrant. On this machine I run a Django development web server:

./manage.py runserver 0.0.0.0:8080

The codebase is big so for faster code reload I installed pyinotify. Django supports it since 1.7. I'm using 1.7.

The codebase sits in a synced folder (NFS) and I'm using Sublime 3 to edit files on my host machine (OS X).

However inotify doesn't go well with NFS and the code autoreload do not work.

How do I restart a dev server in the VM?

1

There are 1 answers

0
Burnash On

I have a rudimentary web server running next to a dev server. This simple web server listens for a request (on a different port) and touches the project's manage.py. This in turn triggers a restart:

reloader.py

#!/usr/bin/env python

import os
import logging
import SocketServer
from BaseHTTPServer import BaseHTTPRequestHandler

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(message)s',
                    datefmt='%m/%d/%Y %I:%M:%S %p')

PORT = 9001
FILE_TO_TOUCH = '/path/to/myenv/manage.py'


def touch(fname, times=None):
    with open(fname, 'a'):
        os.utime(fname, times)


class HandleTouch(BaseHTTPRequestHandler):
    def do_GET(self):
        logging.info("Touching %s", FILE_TO_TOUCH)
        touch(FILE_TO_TOUCH)
        self.send_response(200)
        self.send_header("Content-Length", '0')
        self.end_headers()


httpd = SocketServer.TCPServer(("", PORT), HandleTouch)

logging.info("Server listening on port %s", PORT)

httpd.serve_forever()

On the host machine I use a simple shell command to watch for file changes and hit the reloader's endpoint:

watcher.sh

#!/bin/sh
watchmedo shell-command -c 'curl http://192.168.10.10:9001' -R -i '/path/to/myenv/manage.py' -p '*.py' ./

Where watchmedo is a utility from watchdog.