Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@sbbosco
Last active April 18, 2021 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbbosco/ba61c8d126990a1b24d912f1a4de45ba to your computer and use it in GitHub Desktop.
Save sbbosco/ba61c8d126990a1b24d912f1a4de45ba to your computer and use it in GitHub Desktop.
Dropbox short-lived access token support for Pythonista
# YOU NEED TO INSERT YOUR APP KEY AND SECRET BELOW!
# Go to dropbox.com/developers/apps to create an app.
from __future__ import absolute_import
from __future__ import print_function
import sys, os, json
import webbrowser
import dropbox
import keychain
import requests
from requests.auth import HTTPBasicAuth
# Bosco 2021
# Adds support for Dropbox short-lived OAuth access tokens. Stores long-lived refresh token using the Pythonista keychain module.
#
# Simple use example:
# import dropboxlogin
# dropbox_client = dropboxlogin.get_client()
#
app_key = 'YOUR_APP_KEY'
app_secret = 'YOUR_APP_SECRET'
auth_message = """
1. Browser will open for authorization.
2. Click "Allow" (you might have to log in first).
3. Copy the authorization code.
4. Close Browser.
5. Paste authorization code
"Done" to continue
"""
def dropbox_token(code, grant_type):
if grant_type == 'refresh_token':
data = {'refresh_token': code, 'grant_type': grant_type}
else:
data = {'code':code, 'grant_type':'authorization_code'}
try:
r = requests.post('https://api.dropbox.com/oauth2/token', data=data,
auth = HTTPBasicAuth(app_key, app_secret))
result = r.json()
except:
print(str(sys.exc_info()))
return { 'refresh_token': None, 'access_token': None, 'error': {'.tag': str(sys.exc_info())} }
return result
def get_access_token():
refresh_token = keychain.get_password('dropbox', 'refresh_token')
if not refresh_token:
authorize_url = 'https://www.dropbox.com/oauth2/authorize?response_type=code&token_access_type=offline&client_id=' + app_key
print("1. Go to: " + authorize_url)
print("2. Click \"Allow\" (you might have to log in first).")
print("3. Copy the authorization code.")
if sys.platform == 'ios':
import console, dialogs
do_auth = dialogs.text_dialog(title='Authorize Application', text=auth_message)
if not do_auth: return None
webbrowser.open(authorize_url, modal=True)
auth_code = dialogs.text_dialog(title='authorization code')
else:
webbrowser.open(authorize_url)
auth_code = input("Enter the authorization code here: ").strip()
try:
result = dropbox_token(auth_code, 'authorization_code')
access_token = result['access_token']
refresh_token = result['refresh_token']
except Exception as e:
print('Error: %s' % (e,))
return
keychain.set_password('dropbox', 'refresh_token', refresh_token)
return access_token
access_token = dropbox_token(refresh_token, 'refresh_token')['access_token']
if access_token:
return access_token
return None
def get_client():
access_token = get_access_token()
if not access_token: return None
dbx = dropbox.Dropbox(access_token)
return dbx
def main():
# Demo if started run as a script...
# Just print the account info to verify that the authentication worked:
print('dropbox version', str(dropbox.__version__))
dropbox_client = get_client()
if not dropbox_client:
print('Dropbox client failed...')
return
print(' ')
print('Getting account info...')
account_info = dropbox_client.users_get_current_account()
print('linked account:', account_info)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment