Skip to content

Instantly share code, notes, and snippets.

@mega-arbuz
Last active February 22, 2019 17:30
Show Gist options
  • Save mega-arbuz/5d8734ca69ef3bb852e6dbdfaf76d2fd to your computer and use it in GitHub Desktop.
Save mega-arbuz/5d8734ca69ef3bb852e6dbdfaf76d2fd to your computer and use it in GitHub Desktop.
Upload file to Dropbox and get shareable link
DROPBOX_UPLOAD_ARGS = {
"path": None,
"mode": "overwrite",
"autorename": True,
"strict_conflict": True
}
DROPBOX_UPLOAD_URL = 'https://content.dropboxapi.com/2/files/upload'
DROPBOX_SHARE_DATA = {
"path": None,
"settings": {
"requested_visibility": "public"
}
}
DROPBOX_SHARE_URL = 'https://api.dropboxapi.com/2/sharing/create_shared_link_with_settings'
DROPBOX_DELETE_DATA = {
"path" : None
}
DROPBOX_DELETE_URL = 'https://api.dropboxapi.com/2/files/delete_v2'
def upload_to_dropbox(target_file_name, source_file, dropbox_token, dropbox_folder):
dropbox_path = '/{folder}/{file_name}'.format(folder=dropbox_folder, file_name=target_file_name)
DROPBOX_UPLOAD_ARGS['path'] = dropbox_path
DROPBOX_SHARE_DATA['path'] = dropbox_path
DROPBOX_DELETE_DATA['path'] = dropbox_path
# Try to delete the file before upload
# It's possible to overwrite but this way is cleaner
headers = {'Authorization': 'Bearer ' + dropbox_token,
'Content-Type': 'application/json'}
requests.post(DROPBOX_DELETE_URL, data=json.dumps(DROPBOX_DELETE_DATA), headers=headers)
headers = {'Authorization': 'Bearer ' + dropbox_token,
'Dropbox-API-Arg': json.dumps(DROPBOX_UPLOAD_ARGS),
'Content-Type': 'application/octet-stream'}
# Upload the file
r = requests.post(DROPBOX_UPLOAD_URL, data=open(source_file, 'rb'), headers=headers)
if (r.status_code != requests.codes.ok):
print("Failed: upload file to Dropbox")
return None
headers = {'Authorization': 'Bearer ' + dropbox_token,
'Content-Type': 'application/json'}
# Share and return downloadable url
r = requests.post(DROPBOX_SHARE_URL, data=json.dumps(DROPBOX_SHARE_DATA), headers=headers)
if (r.status_code != requests.codes.ok):
print("Failed: get share link from Dropbox")
return None
# Replace the 'dl=0' at the end of the url with 'raw=1' for direct download and install
return re.sub('dl=.*', 'raw=1', r.json()['url'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment