Create daily snapshots using Python on Digitalocean

In order to use this script, you will need to generate an API key and find your droplet id.
To optain your API KEY you will have to login into your digitalocean account, click on API, then Generate New Token. Once you have it, just update the API_KEY variable.


You can find your droplet id by opening your droplet graphs page ( ). In my case, the droplet id is 123456. After that update the variable DROPLET_ID.


#!/usr/bin/env python
import os
import sys
import requests
import json
import datetime

# Digitalocean variables
API_KEY = ''

API_LIST_SHAPSHOTS = '' + str(DROPLET_ID) + '/snapshots'
API_CREATE_SNAPSHOT = '' + str(DROPLET_ID) + '/actions'

headers = {
    'content-type': 'application/json',
    'Authorization': 'Bearer ' + API_KEY
payload = {}
mode = False
    mode = sys.argv[1]
except Exception as e:

if (mode):
    # Remove the old snapshots
    if mode == 'clean':
        r = requests.get(API_LIST_SHAPSHOTS, data=json.dumps(payload), headers=headers)
        data = r.json()
        snapshots = data['snapshots']
        counter = 1

        if (len(snapshots) > KEEP_SNAPSHOTS - 1):
            for snapshot in reversed(snapshots):
                if counter > KEEP_SNAPSHOTS:
                    print "Removing " + snapshot['name'] + ", having the id : " + str(snapshot['id'])
                    api_url = '' + str(snapshot['id'])
                    r = requests.delete(api_url, data=json.dumps(payload), headers=headers)
                    print r
                    print "Keeping " + snapshot['name']
                counter = counter + 1
    if mode == 'create':
        d = {
            'type': 'snapshot',
            'name': SNAPSHOT_NAME
        r =, data=json.dumps(d), headers=headers)
        print r


How to use this script:

python create # For snapshot creation
python clean # To remove the old snapshot(s)


Linux Python Security
Use Python Requests to Authenticate
Using requests, you can authenticate on a secure website. This method, will also read the CSRF field and cookie, and get it ready for the validation.
Linux Python Django Tutorials
Serve Django Applications with uWSGI and Nginx on CentOS
In this tutorial you will learn how to install and configure VirtualEnv and VirtualEnvWrapper on centos. Also, you will learn how to create your first django application and deploy it.