简体   繁体   English

Python Facebook SDK:获取有关用户朋友的信息

[英]Python Facebook SDK: Getting information about a user's friends

I am trying to extend the example AppEngine application with Facebook login found here . 我正在尝试使用此处找到的Facebook登录名扩展示例AppEngine应用程序。 I was able to get it to work as-is (with my own access token stuff added from a separate file), and it displays this nice little page (brought to you by this example.html ) when a user logs in: 我能够按原样工作(从单独的文件中添加了我自己的访问令牌的东西),并且当用户登录时,它显示了这个漂亮的小页面(由example.html提供给您)。

main.html中

Now, I want to access information about the user's friends; 现在,我想访问有关用户朋友的信息; eg, the movies they have liked. 例如,他们喜欢的电影。 To start, I added the a plethora of permissions to my underlying app on the Facebook developer's dashboard (eg, friends_likes) and then saved changes. 首先,我在Facebook开发人员的仪表板上(例如,friends_likes)向我的基础应用程序添加了过多权限,然后保存了更改。 Then I decided to try displaying a single friend's name, along with his or her favorite movies. 然后,我决定尝试显示一个朋友的名字以及他或她喜欢的电影。 At the moment, I just explicitly store these things with the user and have thus modified the example.py file as follows (new lines end with "###################"): 此刻,我只是将这些内容与用户一起存储,并因此修改了example.py文件,如下所示(新行以“ ####################结尾” ):

#!/usr/bin/env python
#
# Copyright 2010 Facebook
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

"""
A barebones AppEngine application that uses Facebook for login.

1.  Make sure you add a copy of facebook.py (from python-sdk/src/)
    into this directory so it can be imported.
2.  Don't forget to tick Login With Facebook on your facebook app's
    dashboard and place the app's url wherever it is hosted
3.  Place a random, unguessable string as a session secret below in
    config dict.
4.  Fill app id and app secret.
5.  Change the application name in app.yaml.

"""

import facebook
import auth
import webapp2
import os
import jinja2
import urllib2

from google.appengine.ext import db
from webapp2_extras import sessions

config = {}
config['webapp2_extras.sessions'] = dict(secret_key=auth.SESSION_SECRET)


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)
    friend_name = db.StringProperty(required=True) ######################
    friend_movies = db.StringProperty(required=True) ####################

class BaseHandler(webapp2.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 self.session.get("user"):
            # User is logged in
            return self.session.get("user")
        else:
            # Either used just logged in or just saw the first page
            # We'll see here
            cookie = facebook.get_user_from_cookie(self.request.cookies,
                                                   auth.FACEBOOK_APP_ID,
                                                   auth.FACEBOOK_APP_SECRET)
            if cookie:
                # Okay so user logged in.
                # Now, check to see if existing user
                user = User.get_by_key_name(cookie["uid"])
                if not user:
                    # Not an existing user so get user info
                    graph = facebook.GraphAPI(cookie["access_token"])
                    profile = graph.get_object("me")
                    friends = graph.get_connections("me", "friends", fields="name")############
                    fname = friends["data"][0]["name"] ################
                    fid = friends["data"][0]["id"] ################
                    fmov = graph.get_connections(fid, "movies", fields="name")##############
                    user = User(
                        key_name=str(profile["id"]),
                        id=str(profile["id"]),
                        name=profile["name"],
                        friend_name=str(fname),##############
                        friend_movies=str(fmov),##############
                        profile_url=profile["link"],
                        access_token=cookie["access_token"]
                    )
                    user.put()
                elif user.access_token != cookie["access_token"]:
                    user.access_token = cookie["access_token"]
                    user.put()
                # User is now logged in
                self.session["user"] = dict(
                    name=user.name,
                    friend_name = user.friend_name, #################
                    friend_movies=user.friend_movies, ###############
                    profile_url=user.profile_url,
                    id=user.id,
                    access_token=user.access_token
                )
                return self.session.get("user")
        return None

    def dispatch(self):
        """
        This snippet of code is taken from the webapp2 framework documentation.
        See more at
        http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html

        """
        self.session_store = sessions.get_store(request=self.request)
        try:
            webapp2.RequestHandler.dispatch(self)
        finally:
            self.session_store.save_sessions(self.response)

    @webapp2.cached_property
    def session(self):
        """
        This snippet of code is taken from the webapp2 framework documentation.
        See more at
        http://webapp-improved.appspot.com/api/webapp2_extras/sessions.html

        """
        return self.session_store.get_session()


class HomeHandler(BaseHandler):
    def get(self):
        template = jinja_environment.get_template('main.html')
        self.response.out.write(template.render(dict(
            facebook_app_id=auth.FACEBOOK_APP_ID,
            current_user=self.current_user
        )))

    def post(self):
        url = self.request.get('url')
        file = urllib2.urlopen(url)
        graph = facebook.GraphAPI(self.current_user['access_token'])
        response = graph.put_photo(file, "Test Image")
        photo_url = ("http://www.facebook.com/"
                     "photo.php?fbid={0}".format(response['id']))
        self.redirect(str(photo_url))


class LogoutHandler(BaseHandler):
    def get(self):
        if self.current_user is not None:
            self.session['user'] = None

        self.redirect('/')

jinja_environment = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__))
)

app = webapp2.WSGIApplication(
    [('/', HomeHandler), ('/logout', LogoutHandler)],
    debug=True,
    config=config
)

I added a couple of lines to the example.html file to convey the new information: 我在example.html文件中添加了几行来传达新信息:

...

{% if current_user %}
    <p><a href="{{ current_user.profile_url }}">
        <img src="http://graph.facebook.com/{{ current_user.id }}/picture?type=square"/>
    </a></p>
    <p>Hello, {{ current_user.name|escape }}</p>
    <p>You have a friend named {{ current_user.friend_name|escape }}</p>  #################
    <p>Movies your friend likes, probably in some weird format: #################
        {{ current_user.friend_movies }}</p> ##############
{% endif %}

...

For my example Facebook account, which has one friend named "Sey Ian", the output is now: 以我的示例Facebook帐户为例,该帐户有一个名为“ Sey Ian”的朋友,现在的输出为:

在此处输入图片说明

I have two main questions: 我有两个主要问题:

  1. Sey Ian DOES have some liked movies, so why aren't they displaying? 赛伊恩(Sey Ian)有一些喜欢的电影,所以为什么不放映呢? Do I need to do something else permission-related within my code? 我是否需要在代码中做其他与权限相关的事情? Or am I accessing them with the wrong syntax (eg, I need something like friend_movies=str(fmov["data"][0]["name"]) ...for the first movie in this case, kind of like how I access the name of the first friend)? 还是我使用错误的语法访问它们(例如,在这种情况下,对于第一部电影,我需要使用诸如friend_movies=str(fmov["data"][0]["name"])之类的方式...我访问的第一个朋友的名字)?

  2. At some point, I will want to extract even more information about a user and his or her friends. 在某个时候,我将希望提取有关用户及其朋友的更多信息。 With that in mind, are there any nice, THOROUGH examples of Python Facebook SDK graph calls? 考虑到这一点,是否有任何不错的,透彻的Python Facebook SDK图形调用示例? Figuring out how to do just what I have now has taken the good part of FOREVER. 弄清楚如何做我现在所做的事情已经成为了FOREVER的重要部分。

You should have a look at the Firebase authentication page . 您应该查看Firebase身份验证页面 Firebase Authentication provides multiple user authentication options including with Google, Facebook, and Twitter. Firebase身份验证提供了多个用户身份验证选项,包括Google,Facebook和Twitter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM