Programming

Upload a File From Raspberry Pi to Your Dropbox

Updated version of this article: here.

 

Hi,

There are a couple of scripts floating around the Internets you can use to interact with Dropbox from your Raspberry PI.

I find that the easiest way is to use python (the Dropbox client itself is python).

You will need a Dropbox API key which you can get here: https://www.dropbox.com/developers

The following code assumes you have the Dropbox Python SDK available/installed:

#!/usr/bin/python

# Include the Dropbox SDK libraries
from dropbox import client, rest, session
import os
import sys

# Get your app key and secret from the Dropbox developer website
APP_KEY = 'your_api_key'
APP_SECRET = 'your_app_secret'

# ACCESS_TYPE should be 'dropbox' or 'app_folder' as configured for your app
ACCESS_TYPE = 'app_folder'

sess = session.DropboxSession(APP_KEY, APP_SECRET, ACCESS_TYPE)

if os.path.exists('token.txt'):
        token_file = open('token.txt', 'rb')
        key = token_file.read(15)
        secret = token_file.read(15)
        token_file.close()

        sess.set_token(key, secret)
else:
        request_token = sess.obtain_request_token()
        # Make the user sign in and authorize this token
        url = sess.build_authorize_url(request_token)
        print "url:", url
        print "Please authorize in the browser. After you're done, press enter."
        raw_input()

        # This will fail if the user didn't visit the above URL and hit 'Allow'
        access_token = sess.obtain_access_token(request_token)

        if (access_token):
                #print access_token.key
                #print access_token.secret
                token_file = open('token.txt', 'wb')
                token_file.write(access_token.key)
                token_file.write(access_token.secret)
                token_file.close()

client = client.DropboxClient(sess)
# print "linked account:", client.account_info()

noParams = len(sys.argv)
if noParams < 2:
        print "Usage: upload_to_dropbox.py <file1> ..."
        sys.exit(0)

for idx in range(1, noParams):
        f = open(sys.argv[idx])
        filename = os.path.basename(sys.argv[idx])
        response = client.put_file(filename, f, True)
        print "uploaded:", response

The secret sauce to this python is that the auth token is saved in a .txt file.

If you don’t have GUI access on your Raspberry PI(like me) you will have to run the script in a desktop environment first and copy over the resulting token.txt which contains your OAuth token.

The token doesn’t really ever expire so no worries, there’s no sugar.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.