Itsy Bitsy Bytes


on python, ghost

Backing up Ghost blogs with Python

Having an up to date backup of your blog is very important if you don't want to end up crying for your data in case something goes horribly, horribly wrong.
Importing and exporting a Ghost blog's settings and data is as easy as pressing a button but the truly hard part is bothering yourself to do it.

While easy, you still have to 1) go to your admin panel, 2) click on "Labs", 3) click on "Export" and 4) keeping track of the downloaded json file. That's four steps, five if you also have to log in beforehand. And imagine doing it for any other blog you might have...

That is not a programmer's way! The programmer's way is to have a script do it for you. Just run it every time it's needed and get on with your life. And that's exactly what I did for my Ghost blogs with the help of Python.

The trickiest part was to discover how to remotely replicate the Ghost login & backup process. Initially I wanted to simulate the user's page interaction but after some fiddling around the Network tab I discovered an easier solution. You only need two requests: one to generate an access token and another one towards the backup API, which will return the desired json file.

ghost login page
First I watched what happens during the login.

Ghost access token
And then I figured out how to get the token. When analyzing the login request, make sure to note the client_secret, it will be necessary for the token request.

Speaking about the devil, the mighty token is retrieved with a simple POST request at ghost/api/v0.1/authentication/token/ with the following payload:

{
    'grant_type': 'password',
    'client_id': 'ghost-admin',
    'client_secret': 'your_client_secret',
    'username': 'your_username',
    'password': 'your_password'
}

Connecting to the blog was by far the easiest part, since the Python requests library does all the heavy lifting.

What was once a tedious (arguably) process of remembering to back up my blogs is now replaced by a simple python backup.py call and it makes sure to download a fresh database copy of my data.

ghost backup script

For those interested, the code for the script is open source and on Github: Ghost Backup Script. The official project page is here: Ghost Backup Script, including detailed instructions, as well as an automatic config generator.


comments powered by Disqus