Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto restart django development server on file save after previous error

Tags:

python

django

While writing the code, I usually am in the habit of saving the file every minute or so. Sometimes, that leads to situations where the function is not complete, and I have saved it, causing the django development server to throw up an error like following:

Unhandled exception in thread started by ...
Traceback
..
..
  File "/home/user/work/project/api/file.py", line 26
      def update_something(self, ) 
                               ^
SyntaxError: invalid syntax

Now in cases when the code is working fine, the django dev server auto-restarts on file save with reflected changes. How can I make the django server recover from the failed Error state and restart the server automatically on subsequent file saves?

Currently, I have to stop the python manage.py runserver command in terminal, and run it manually again.

I am using django 1.5.3 on python 2.7.6

like image 286
Anshul Goyal Avatar asked Aug 08 '14 08:08

Anshul Goyal


1 Answers

I use a simple bash script for this. Here's a one-liner you can use:

$ while true; do python manage.py runserver; sleep 2; done

That will wait 2 seconds before attempting to restart the server. Insert whatever you think is a sane value.

I usually write this as a shell script named runserver.sh, put it in my project root (the same directory with manage.py in it) and add it to the gitignore.

while true; do
  echo "Re-starting Django runserver"
  python manage.py runserver
  sleep 2
done

If you do this, remember to chmod +x runserver.sh, then you can execute it with:

./runserver.sh

Use Ctrl-c Ctrl-c to exit.

like image 84
Nick Frezynski Avatar answered Oct 17 '22 15:10

Nick Frezynski