Skip to content Skip to sidebar Skip to footer

Build Directory Tree From Dropbox Api

What I'd like to do is to build a tree from the dropbox API, for a given path, with share links for each path, using the python bindings. My proposed structure looks something like

Solution 1:

I tweaked your structure just a bit... here's the JSON representation of what the below code produces. Note that I've made the contents field a dictionary indexed by path instead of an array. This is just a little easier and makes for more efficient lookup, but it should be pretty easy to convert to exactly what you have above if you want:

{"is_dir":true,"contents":{"/foo.txt":{"is_dir":false,"contents":{}},"/a":{"is_dir":true,"contents":{"/a/bar.txt":{"is_dir":false,"contents":{}},"/a/b":{"is_dir":true,"contents":{"/a/b/hello.txt":{"is_dir":false,"contents":{}}}}}}}}

Here's the code that produces that output:

ACCESS_TOKEN = '<REDACTED>'from collections import defaultdict
import json

from dropbox.client import DropboxClient

defmake_tree():
    return {
        'is_dir': True,
        'contents': defaultdict(make_tree)
    }
tree = defaultdict(make_tree)

client = DropboxClient(ACCESS_TOKEN)

has_more = True
cursor = Nonewhile has_more:
    delta = client.delta(cursor)

    cursor = delta['cursor']
    has_more = delta['has_more']

    for path, metadata in delta['entries']:
        if metadata isnotNone:

            # find the right place in the tree
            segments = path.split('/')
            location = tree['/']
            for i in xrange(1, len(segments)-1):
                current_path = '/'.join(segments[:i+1])
                location = location['contents'][current_path]

            # insert the new entry
            location['contents'][path] = {
                'is_dir': metadata['is_dir'],
                'contents': {}
            }

print json.dumps(tree['/'], indent=4)

Post a Comment for "Build Directory Tree From Dropbox Api"