def set_current_user_from_post(self): if not hasattr(self, "_current_user"): self._current_user = None signed_req = self.request.get('signed_request') logging.debug('signed_req:' + signed_req) (encoded_sig, payload) = signed_req.split('.') sig = base64_decode(encoded_sig) data_str = base64_decode(payload) #logging.debug("(sig,payload) = (%s,%s)" % (sig,data_str)) data = facebook._parse_json(data_str) if data['user_id']: # Store a local instance of the user data so we don't need # a round-trip to Facebook on every request user = User.get_by_key_name(data['user_id']) access_token = data['oauth_token'] if not user: logging.debug("no current user in db. adding user of id %s, access_token:%s" % (data['user_id'], access_token)) graph = facebook.GraphAPI(access_token) profile = graph.get_object("me") user = User(key_name=str(profile["id"]), id=str(profile["id"]), name=profile["name"], profile_url=profile["link"], access_token=access_token) user.put() elif user.access_token != access_token: logging.debug("new access token for user %s(%s): %s" % (user.name,data['user_id'],access_token)) user.access_token = access_token user.put() self._current_user = user
def simple_request(path): """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. """ try: file = urlopen(path) except HTTPError, e: response = facebook._parse_json(e.read()) raise facebook.GraphAPIError(response)
def graph_put_file(self, path, argname, filename, file, **post_args): """put a file to facebook. - argname : api name, probably 'source' - filename: name of file itself, i.e. foo.jpg """ form = MultipartForm.MultiPartForm() form.add_field("access_token", self.current_user.access_token) for a in post_args: logging.debug("putting arg %s:%s" % (a, post_args[a])) form.add_field(a, post_args[a]) form.add_file(argname, filename, file) req = urllib2.Request("https://graph.facebook.com/" + path) body = str(form) req.add_header("Content-type", form.get_content_type()) req.add_header("Content-length", len(body)) req.add_data(body) s = urllib2.urlopen(req).read() return facebook._parse_json(s)
"""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. """ try: file = urlopen(path) except HTTPError, e: response = facebook._parse_json(e.read()) raise facebook.GraphAPIError(response) try: fileInfo = file.info() if fileInfo.maintype == 'text': response = facebook._parse_json(file.read()) elif fileInfo.maintype == 'image': mimetype = fileInfo['content-type'] response = { "data": file.read(), "mime-type": mimetype, "url": file.url, } else: raise facebook.GraphAPIError('Maintype was not text or image') finally: file.close() if response and isinstance(response, dict) and response.get("error"): raise GraphAPIError(response["error"]["type"], response["error"]["message"])