facebook.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import requests
  2. import urllib
  3. import simplejson as json
  4. import pdb
  5. ##########################
  6. # FACEBOOK API CONSTANTS #
  7. ##########################
  8. AUTHORIZE_URL = 'https://graph.facebook.com/oauth/authorize'
  9. ACCESS_TOKEN_URL = 'https://graph.facebook.com/oauth/access_token'
  10. class FacebookOauthClient(object):
  11. '''
  12. Python client for Facebook API
  13. '''
  14. access_token = None
  15. def __init__(self, client_id, client_secret):
  16. '''
  17. Parameters:
  18. client_id: String
  19. - The client id from the registering app on Facebook
  20. client_secret: String
  21. - The client secret from the registering app on Facebook
  22. '''
  23. self.client_id = client_id
  24. self.client_secret = client_secret
  25. def get_authorize_url(self):
  26. '''
  27. Obtains authorize url link with given client_id.
  28. Returns:
  29. authURL: String
  30. - The authorization url.
  31. '''
  32. authSettings = {'redirect_uri': "http://localhost:8000/hackathon/",
  33. 'client_id': self.client_id}
  34. params = urllib.urlencode(authSettings)
  35. return AUTHORIZE_URL + '?' + params
  36. def get_access_token(self, code):
  37. '''
  38. Obtains access token.
  39. Parameters:
  40. code: String
  41. - The code is retrieved from the authorization url parameter
  42. to obtain access_token.
  43. '''
  44. authSettings = {'code': code,
  45. 'redirect_uri': "http://localhost:8000/hackathon/",
  46. 'client_secret': self.client_secret,
  47. 'client_id': self.client_id}
  48. params = urllib.urlencode(authSettings)
  49. response = requests.get(ACCESS_TOKEN_URL + '?' + params)
  50. if response.status_code != 200:
  51. raise(Exception('Invalid response,response code: {c}'.format(c=response.status_code)))
  52. response_array = str(response.text).split('&')
  53. self.access_token = str(response_array[0][13:])
  54. def get_user_info(self):
  55. '''
  56. Obtains user information.
  57. Returns:
  58. content: Dictionary
  59. - A dictionary containing user information.
  60. '''
  61. response = requests.get("https://graph.facebook.com/me?access_token={at}".format(at=self.access_token))
  62. if response.status_code != 200:
  63. raise(Exception('Invalid response,response code: {c}'.format(c=response.status_code)))
  64. return response.json()