I’ve been using the gunicorn WSGI server lately while I work on my next project. gunicorn is fantastic, except for one tiny nuisance. I have to restart gunicorn as I change my app code. At the beginning, this meant I would switch over to the terminal where gunicorn was running. Then I’d kill the parent process by hitting CTRL+C, and then start it up again, by typing:
Other frameworks often have a development mode that forks off a helper process that watches the source code folder. When some file changes, the helper tells the server to reload.
I’m not using any frameworks this time, so I don’t have that feature. I never really liked the fact that every time I saved a file, I would restart the server during development. Instead, in this case, I want to easily restart gunicorn, but only when I want to, and I don’t want to leave my editor.
It turned out to be pretty easy to do.
First I read in the excellent gunicorn docs how to tell gunicorn to reload my app:
How do I reload my application in Gunicorn?
You can gracefully reload by sending HUP signal to gunicorn:
$ kill -HUP masterpid
Next I added a –pid /tmp/gunicorn.pid option to the command that I use to start gunicorn, so that gunicorn would write the parent’s process ID into /tmp/gunicorn.pid.
Now any time I want gunicorn to reload, I can do this little command in a terminal window:
$ kill -HUP `cat /tmp/gunicorn.pid`
Those backticks around cat /tmp/gunicorn.pid tell the shell to do that part of the command first, and then feed the result into the rest of the command.
You can always use ! in vim to run some command-line program. If I had to explain the difference between vim and emacs, the one difference that is most interesting to me is that vim makes it super-easy to send buffer contents to other programs or read buffer contents from other programs, while the people behind emacs seem to think that any external dependency should ultimately be moved into emacs itself. I get the feeling that vim wants to be my text editor, but emacs wants to be my OS.
Anyhow, while I’m in vim, I run that command to restart like this:
: !kill -HUP `cat /tmp/gunicorn.pid`
After using that code for a while, and feeling confident it worked right, I mapped F12 in vim to do that action for me by adding this little thing to the end of my ~/.vimrc:
:map <F12> :!kill -HUP `cat /tmp/gunicorn.pid`<CR>
Now that means I hit F12 when I want to reload gunicorn.