How do I parse the JSON array when trying to load facebook friends into Google App Engine facebook example?
I am just starting out on an idea of a Google App engine app that interacts with Facebook. All my coding experience is number crunching in Matlab, which is so high level, a lot of real coders haven't even heard of it. I am attempting to extend the example provided by facebook here. So far, the only thing I've tried to add is reading in a list of the user's friends. I've put comments ahead of the lines I added in my version of the code below. The code succeeds in loading in the user from facebook. I can access the various user properties and display them. However, the friends property that I tried to add is always a blank list. I think the difference is that things like name and id are JSON strings that can be handled like Python strings but graph.get_connections returns an array of JSON objects as the list of friends. I think I should be turning this JSON array into a python dictionary but I don't know how. Of course, I may be completely wrong about that.
I would really appreciate a tip as to how I can get the user's list of friends into a python list of some kind that I can manipulate.
Thanks,
Dessie
#!/usr/bin/env python
#
# Copyright 2010 Facebook
#
"""A barebones AppEngine application that uses Facebook for login."""
FACEBOOK_APP_ID = "my_facebook_app_id"
FACEBOOK_APP_SECRET = "my_facebook_app_secret"
import facebook
import os.path
import wsgiref.handlers
import logging
import platform
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.ext.webapp import template
class User(db.Model):
id = db.StringProperty(required=True)
created = db.DateTimeProperty(auto_now_add=True)
updated = db.DateTimeProperty(auto_now=True)
name = db.StringProperty(required=True)
profile_url = db.StringProperty(required=True)
access_token = db.StringProperty(required=True)
#Following line added by me
friends = db.StringListProperty()
class BaseHandler(webapp.RequestHandler):
"""Provides access to the active Facebook user in self.current_user
The property is lazy-loaded on first access, using the cookie saved
by the Facebook JavaScript SDK to determine the user ID of the active
user. See http://developers.facebook.com/docs/authentication/ for
more information.
"""
@property
def current_user(self):
if not hasattr(self, "_current_user"):
self._current_user = None
cookie = facebook.get_user_from_cookie(
self.request.cookies, FACEBOOK_APP_ID, FACEBOOK_APP_SECRET)
if cookie:
# 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(cookie["uid"])
if not user:
graph = facebook.GraphAPI(cookie["access_token"])
profile = graph.get_object("me")
id=str(profile["id"]
#Following 2 lines added by me
fs=graph.get_connections("me","friends")
logging.info(fs)
user = User(key_name=str(profile["id"]),
id=str(profile["id"]),
name=profile["name"],
profile_url=profile["link"],
access_token=cookie["access_token"],
#Following line added by me
friends=fs)
user.put()
elif user.access_token != cookie["access_token"]:
开发者_开发百科 user.access_token = cookie["access_token"]
user.put()
self._current_user = user
return self._current_user
class HomeHandler(BaseHandler):
def get(self):
#Following line added by me
logging.info(self.current_user.friends)
path = os.path.join(os.path.dirname(__file__), "example.html")
args = dict(current_user=self.current_user,
facebook_app_id=FACEBOOK_APP_ID)
self.response.out.write(template.render(path, args))
def main():
util.run_wsgi_app(webapp.WSGIApplication([(r"/", HomeHandler)]))
if __name__ == "__main__":
main()
I think I should be turning this JSON array into a python dictionary but I don't know how.
simplejson is included in app-engine, in django's utils package.
from django.utils import simplejson as json
def your_method(ars):
# do what ever you are doing...
dict_of_friends = json.loads(json_string)
Having trouble with commenting tool, the time limit is throwing me off. Robert's answer seems right but it didn't work in my script. I finally got it to work with a different approach
import re
import urllib2
#after I created the user
url = "https://graph.facebook.com/" + user.id + "/friends?access_token=" + user.access_token
response = urllib2.urlopen(url)
fb_response = response.read()
x = re.findall(r'"\d+"',fb_response)
friend_list = [a.strip('"') for a in x]
user.friends = friend_list
user.put()
You don't have to convert explicitly from json at facebook python library.
just start from fs["data"], for example if you want to count the number of friends.
fs=graph.get_connections("me","friends")
friends_count = len(fs["data"])
精彩评论