Skip to content

Instantly share code, notes, and snippets.

@oldcai
Created December 30, 2013 10:55
Show Gist options
  • Save oldcai/8180635 to your computer and use it in GitHub Desktop.
Save oldcai/8180635 to your computer and use it in GitHub Desktop.
A dropbox read only client
#coding:utf-8
import os
import dropbox
app_key = 'app_key'
app_secret = 'app_secret'
def load_access_token():
if os.path.isfile("access_token"):
with open("access_token") as f:
access_token = f.read().strip()
return access_token
def login():
flow = dropbox.client.DropboxOAuth2FlowNoRedirect(app_key, app_secret)
authorize_url = flow.start()
print '1. Go to: ' + authorize_url
print '2. Click "Allow" (you might have to log in first)'
print '3. Copy the authorization code.'
code = raw_input("Enter the authorization code here: ").strip()
access_token, user_id = flow.finish(code)
with open("access_token", "w") as f:
f.write(access_token)
return access_token
client = None
def get_client(access_token=None):
global client
if access_token:
client = dropbox.client.DropboxClient(access_token)
if not client:
access_token = load_access_token()
if not access_token:
access_token = login()
client = get_client(access_token)
return client
def get_file(path):
try:
response = get_client().get_file(path)
except dropbox.rest.ErrorResponse as e:
if 401 == e.status:
print "Access token expired, login again"
access_token = login()
client = get_client(access_token)
response = client.get_file(path)
return response
def get_file_content(path):
response = get_file(path)
return response.read()
def main():
print get_file_content('/Documents/test_file.txt')
response = get_file('/Documents/test_file.txt')
line_num = 1
while True:
line = response.readline()
print "# %d:" % line_num, line
line_num += 1
if not line:
break
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment