In [ ]:
import requests
import datetime
import pandas as pd
import json

baseurl = 'https://api.digitalocean.com/v2/'

headers = {
"content-type":"application/json",
"Authorization":"Bearer SECRET KEY",
}


def get_snapshots():
    url = baseurl+'snapshots?resource_type=droplet'
    r=requests.get(url, headers=headers)
    return r.json()

def delete_snapshot(snapshot_id):
    url = baseurl + 'snapshots/'+str(snapshot_id)
    r = requests.delete(url, headers=headers)
    return r

def snapshot(droplet_id,droplet_name):
    url = baseurl + 'droplets/'+str(droplet_id)+'/actions'
    payload = {'type': 'snapshot', 'name': droplet_name + '_' + str(datetime.date.today())}
    r = requests.post(url, headers=headers, data=json.dumps(payload))
    return r.json()

def get_droplets():
    url = baseurl+'droplets'
    r=requests.get(url, headers=headers)
    return r.json()

try:
    droplets = get_droplets()
except Exception as e:
    exit(str(e))

for droplet in droplets['droplets']:
    try:
        if (droplet['status']=='active' and droplet['locked']== False):
            response = snapshot(droplet_id=droplet['id'],droplet_name=droplet['name'])
            # raise ValueError('A very specific bad thing happened')
            if (response['action']['status'] == 'in-progress'):
                print ('Snapshot of droplet ' + droplet['name'] + ' was queued successfully\n')
            else:
                print ('There was an error in queing the snapshot of droplet ' + droplet['name'] + '\n')
    except Exception as e:
        exit(str(e))
        print(str(e))

try:
    snapshots = get_snapshots()
except Exception as e:
    exit(str(e))


df = pd.DataFrame(snapshots['snapshots'])
backup_length = 7

for droplet in list(df.resource_id.unique()):
    snap_df = df[(df['resource_id']==droplet) & (df['name'].apply(lambda x: False if 'protect' in x else True))]

    if snap_df.shape[0] > backup_length:
        snap_df = snap_df.sort_values(by='created_at', ascending=False)
        snapshots_delete = snap_df.iloc[0:snap_df.shape[0]-backup_length]
        for snapshot_delete in list(snapshots_delete.id.unique()):
            delete_snapshot(snapshot_delete)
            print ('Snapshot with the following number deleted successfully: ' + str(snapshot_delete) + '\n')