Uploading to Dropbox with Python

July 21, 2010

I've been searching for an easy way to backup some files that are located on my web server. I use Dropbox to backup lots of important files on my computer, but I don't want to have this software running on my web server for security and performance reasons. So, I used Python to automate the process of uploading a file via the web interface.

The process is pretty simple. The following example code doesn't actually work anymore due to minor updates tot the Dropbox website, so please head to github for the working version. The following provides a brief overview of how the guts work in general.

First, I'll be using mechanize to create a browser session.

br = mechanize.Browser()

Then I open up the Dropbox login page.

br.open('https://www.dropbox.com/login')

Now I need to find the proper form to enter the credentials into. For that, I use a lamda function which checks the form action.

isLoginForm = lambda f: f.action == "https://www.dropbox.com/login"
br.select_form(predicate=isLoginForm)

Now that I have the right form, I just set my credentials and submit.

br["login_email"] = email
br["login_password"] = password
response = br.submit()

I'm now logged in to Dropbox. I need to find the file upload form. I also did this with a lamda function to check the action.

isUploadForm = lambda f: f.action == "https://dl-web.dropbox.com/upload"
br.select_form(predicate=isUploadForm)

Now I just fill out that with the proper destination and file to upload and submit it. The destination path is read only, so that needs be changed before it can be overwritten with a new destination.

br.form.find_control("dest").readonly = False
br.form.set_value(remote_dir,"dest")
br.form.add_file(open(local_file),"",remote_file)

br.submit()

If all went well, the file will be uploaded to Dropbox. The code for this is available as a small Python package on github.

Check out my other pages tagged "blog".