Using LiveReload with Pelican
Posted on 16 June 2015 in misc
LiveReload is magic. As the authors describe it:
The Web Developer Wonderland
(a happy land where browsers don't need a Refresh button) -- LiveReload
What does it do? It's a browser plugin that automatically refreshes a page when the server tells it to. On the other side, we have a web server that monitors file changes, runs a 'compile' step and sends a 'reload' message once the compile step is complete. In the case of Pelican, this means:
- monitor the content directory for changes,
- when files change, run Pelican, and
- once Pelican is done, tell the browser new files are ready.
The web server we use for this is python-livereload, as it allows us to configure the compile step in Python. After all, Pelican is written in Python, and allows us to call it as a library.
Running a Pelican compilation from Python is fairly simple:
from pelican import Pelican
from pelican.settings import read_settings
p = Pelican(read_settings('pelicanconf.py'))
try:
p.run()
except SystemExit:
# something went wrong in the compilation, but that's OK
pass
Where we catch SystemExit because of a bug in how the rst parser is called.
Combining this with the Sphinx example from the python-livereload docs, we get the following file, pelican-livereload.py:
from livereload import Server, shell
from pelican import Pelican
from pelican.settings import read_settings
p = Pelican(read_settings('pelicanconf.py'))
def compile():
try:
p.run()
except SystemExit as e:
pass
server = Server()
server.watch('content/', compile)
server.serve(root='output')
Running this will start the server on port 5500:
[I 150616 20:34:53 server:271] Serving on http://127.0.0.1:5500 [I 150616 20:34:53 handlers:58] Start watching changes [I 150616 20:34:53 handlers:60] Start detecting changes
After installing the browser plugin, visit http://127.0.0.1:5500 to view your blog. Start editing files, save them and poof, your browser magically reloads. It's the best thing since sliced bread!
Note, though, that compile errors won't show up in your browser, but in the terminal. The browser will refresh, but no new content will be shown.