How to get user posts through facebook-sdk python api?

我只是一个虾纸丫 提交于 2019-12-04 05:12:25

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

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]

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")

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!