def get_app_access_token(app_id, app_secret): """Get the access_token for the app. This token can be used for insights and creating test users. app_id = retrieved from the developer page app_secret = retrieved from the developer page Returns the application access_token. """ # Get an app access token args = {'grant_type': 'client_credentials', 'client_id': app_id, 'client_secret': app_secret} file = urllib2.urlopen("https://graph.facebook.com/oauth/access_token?" + uni_urlencode(args)) try: result = file.read().split("=")[1] finally: file.close() return result
def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/roadmap/offline-access-removal/ #extend_token> """ args = { "client_id": app_id, "client_secret": app_secret, "grant_type": "fb_exchange_token", "fb_exchange_token": self.access_token, } response = urllib.urlopen("https://graph.facebook.com/oauth/" "access_token?" + uni_urlencode(args)).read() query_str = parse_qs(response) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] return result else: response = json.loads(response) raise GraphAPIError(response)
def get_access_token_from_code(code, redirect_uri, app_id, app_secret): """Get an access token from the "code" returned from an OAuth dialog. Returns a dict containing the user-specific access token and its expiration date (if applicable). """ args = { "code": code, "redirect_uri": redirect_uri, "client_id": app_id, "client_secret": app_secret, } # We would use GraphAPI.request() here, except for that the fact # that the response is a key-value pair, and not JSON. response = urllib.urlopen("https://graph.facebook.com/oauth/access_token" + "?" + uni_urlencode(args)).read() query_str = parse_qs(response) if "access_token" in query_str: result = {"access_token": query_str["access_token"][0]} if "expires" in query_str: result["expires"] = query_str["expires"][0] return result else: response = json.loads(response) raise GraphAPIError(response)
def fql(self, query, args=None, post_args=None): """FQL query. Example query: "SELECT affiliations FROM user WHERE uid = me()" """ args = args or {} if self.access_token: if post_args is not None: post_args["access_token"] = self.access_token else: args["access_token"] = self.access_token post_data = None if post_args is None else uni_urlencode(post_args) """Check if query is a dict and use the multiquery method else use single query """ if not isinstance(query, basestring): args["queries"] = query fql_method = 'fql.multiquery' else: args["query"] = query fql_method = 'fql.query' args["format"] = "json" try: file = urllib2.urlopen("https://api.facebook.com/method/" + fql_method + "?" + uni_urlencode(args), post_data, timeout=self.timeout) except TypeError: # Timeout support for Python <2.6 if self.timeout: socket.setdefaulttimeout(self.timeout) file = urllib2.urlopen("https://api.facebook.com/method/" + fql_method + "?" + uni_urlencode(args), post_data) try: content = file.read() response = _parse_json(content) #Return a list if success, return a dictionary if failed if type(response) is dict and "error_code" in response: raise GraphAPIError(response) except Exception, e: raise e
def auth_url(app_id, canvas_url, perms=None, state=None): url = "https://www.facebook.com/dialog/oauth?" kvps = {'client_id': app_id, 'redirect_uri': canvas_url} if perms: kvps['scope'] = ",".join(perms) if state: kvps['state'] = state return url + uni_urlencode(kvps)
def request(self, path, args=None, post_args=None): """Fetches the given path in the Graph API. We translate args to a valid query string. If post_args is given, we send a POST request to the given path with the given arguments. """ args = args or {} if self.access_token: if post_args is not None: post_args["access_token"] = self.access_token else: args["access_token"] = self.access_token post_data = None if post_args is None else uni_urlencode(post_args) try: file = urllib2.urlopen("https://graph.facebook.com/" + path + "?" + uni_urlencode(args), post_data, timeout=self.timeout) except urllib2.HTTPError, e: response = _parse_json(e.read()) raise GraphAPIError(response)
def delete_request(self, user_id, request_id): """Deletes the Request with the given ID for the given user.""" conn = httplib.HTTPSConnection('graph.facebook.com') url = '/%s_%s?%s' % ( request_id, user_id, uni_urlencode({'access_token': self.access_token}), ) conn.request('DELETE', url) response = conn.getresponse() data = response.read() response = _parse_json(data) # Raise an error if we got one, but don't not if Facebook just # gave us a Bool value if (response and isinstance(response, dict) and response.get("error")): raise GraphAPIError(response) conn.close()
else: args["access_token"] = self.access_token post_data = None if post_args is None else uni_urlencode(post_args) try: file = urllib2.urlopen("https://graph.facebook.com/" + path + "?" + uni_urlencode(args), post_data, timeout=self.timeout) except urllib2.HTTPError, e: response = _parse_json(e.read()) raise GraphAPIError(response) except TypeError: # Timeout support for Python <2.6 if self.timeout: socket.setdefaulttimeout(self.timeout) file = urllib2.urlopen("https://graph.facebook.com/" + path + "?" + uni_urlencode(args), post_data) try: fileInfo = file.info() if fileInfo.maintype == 'text': response = _parse_json(file.read()) elif fileInfo.maintype == 'image': mimetype = fileInfo['content-type'] response = { "data": file.read(), "mime-type": mimetype, "url": file.url, } else: raise GraphAPIError('Maintype was not text or image') finally: file.close()