python - 尝试将 facebook 好友加载到 Google App Engine facebook 示例时如何解析 JSON 数组?

标签 python json facebook google-app-engine

我刚刚开始构想与 Facebook 交互的 Google App 引擎应用程序。我所有的编码经验都是在 Matlab 中进行数字运算,这是非常高级的,很多真正的编码人员甚至都没有听说过它。我正在尝试扩展 facebook here 提供的示例.到目前为止,我尝试添加的唯一一件事就是阅读用户的好友列表。我在下面的代码版本中添加的行之前添加了注释。该代码成功地从 facebook 加载用户。我可以访问各种用户属性并显示它们。但是,我尝试添加的 friends 属性始终是一个空白列表。我认为不同之处在于 name 和 id 之类的东西是 JSON 字符串,可以像 Python 字符串一样处理,但是 graph.get_connections 返回一个 JSON 对象数组作为 friend 列表。我想我应该把这个 JSON 数组变成一个 python 字典,但我不知道怎么做。当然,我可能完全错了。

关于如何将用户的 friend 列表放入我可以操作的某种 python 列表中的提示,我将非常感激。

谢谢,

黛西

#!/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 包含在 app-engine 中,在 django 的 utils 包中。

from django.utils import simplejson as json

def your_method(ars):
   # do what ever you are doing...
   dict_of_friends = json.loads(json_string)

关于python - 尝试将 facebook 好友加载到 Google App Engine facebook 示例时如何解析 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4355762/

相关文章:

python - 从 Keras 调用方法 timeseries_dataset_from_array 时出错

javascript - 强制 ember-data 从服务器重新加载特定记录

android - Facebook api并向android中的多个 friend 发送邀请

ios - 如何将 facebook 注销按钮移动到其他导航/ View Controller 包?

Python pytz 与 DST 的问题

python - 我如何在 python 中拥有 "press enter to continue"功能?

python - 如何使用 Python 截取网站的屏幕截图/图像?

java - jackson json 与 hibernate : jackson-module-hibernate usage

json - Curl 和 jq 替换值中的子字符串

javascript - 在后端脚本后重定向到一个新的 url