dropbox.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import simplejson as json
  2. import urllib
  3. import requests
  4. import string
  5. import pdb
  6. import random
  7. AUTHORIZE_URL = 'https://www.dropbox.com/1/oauth2/authorize'
  8. ACCESS_TOKEN_URL = 'https://api.dropbox.com/1/oauth2/token'
  9. class DropboxOauthClient(object):
  10. access_token = None
  11. session_id = None
  12. def __init__(self, client_id, client_secret):
  13. self.client_id = client_id
  14. self.client_secret = client_secret
  15. def get_authorize_url(self):
  16. self.get_session_id()
  17. authSettings = {'response_type': 'code',
  18. 'client_id': self.client_id,
  19. 'redirect_uri': 'http://localhost:8000/hackathon',
  20. 'state': self.session_id}
  21. params = urllib.urlencode(authSettings)
  22. return AUTHORIZE_URL + '?' + params
  23. def get_session_id(self, length=50):
  24. chars = string.uppercase + string.digits + string.lowercase
  25. self.session_id = ''.join(random.choice(chars) for _ in range(length))
  26. def get_access_token(self, code, state):
  27. if state != self.session_id:
  28. raise(Exception('Danger! Someone is messing up with you connection!'))
  29. authSettings = {'code': code,
  30. 'grant_type': 'authorization_code',
  31. 'client_id': self.client_id,
  32. 'client_secret': self.client_secret,
  33. 'redirect_uri': 'http://localhost:8000/hackathon'}
  34. response = requests.post(ACCESS_TOKEN_URL, data=authSettings)
  35. if response.status_code!=200:
  36. raise(Exception('Invalid response, response code {c}'.format(c=response.status_code)))
  37. self.access_token = response.json()['access_token']
  38. def get_user_info(self):
  39. USER_INFO_API = 'https://api.dropbox.com/1/account/info'
  40. params = urllib.urlencode({'access_token': self.access_token})
  41. response = requests.get(USER_INFO_API + '?' + params)
  42. if response.status_code!=200:
  43. raise(Exception('Invalid response, response code {c}'.format(c=response.status_code)))
  44. return response.json()