且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过Facebook-sdk python api获取用户的帖子?

更新时间:2023-12-03 16:09:34

你想知道如何使用python api获取用户的帖子吧?

You want to know how to get user posts using a python api, right?

我正在使用 facebook-sdk 在django项目中,我得到它的工作,像这样(Implementation - services / facebook.py):

I'm using facebook-sdk within a django project and I got it to work, like this (Implementation - services/facebook.py):

from django.conf import settings
import facebook
import requests

class FacebookFeed:
    token_url = 'https://graph.facebook.com/oauth/access_token'
    params = dict(client_id=settings.SOCIAL_AUTH_FACEBOOK_KEY, client_secret=settings.SOCIAL_AUTH_FACEBOOK_SECRET,
                  grant_type='client_credentials')

    @classmethod
    def get_posts(cls, user, count=6):
        try:
            token_response = requests.get(url=cls.token_url, params=cls.params)
            access_token = token_response.text.split('=')[1]
            graph = facebook.GraphAPI(access_token)
            profile = graph.get_object(user)
            query_string = 'posts?limit={0}'.format(count)
            posts = graph.get_connections(profile['id'], query_string)
            return posts
        except facebook.GraphAPIError:
            return None

注意:在我的情况下,如果您将用户登录到您的应用程序并已具有令牌,则需要使用客户端凭据流来使用密钥和密码设置来获取访问令牌在你身边,然后忽略这些行:

Note: In my case I need to fetch the access token using the client-credentials flow, making use of the Key and Secret settings, if you're logging users into an app of yours and already have tokens on your side, then ignore the lines:

token_response = requests.get(url=cls.token_url, params=cls.params)
access_token = token_response.text.split('=')[1]

(views.py):

Usage (views.py):

from django.http import HttpResponse
from app.services.social_networks.facebook import FacebookFeed

def get_facebook_posts(request, user):
    posts = FacebookFeed.get_posts(user=user)
    if not posts:
        return HttpResponse(status=500, content="Can't fetch posts for desired user", content_type="application/json")
    return HttpResponse(json.dumps(posts), content_type="application/json")

希望这有帮助,任何问题,请问ask =)

Hope this helps, any problem, please do ask =)