Created
March 1, 2013 15:06
-
-
Save aschem/5065233 to your computer and use it in GitHub Desktop.
Server to server Facebook OAuth2 client.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
APP_ID = '' | |
APP_SECRET = '' | |
APP_ACCESS_TOKEN = '' | |
def do_request(url, **kwargs): | |
""" Does request Facebook API request. """ | |
r = requests.get('https://graph.facebook.com/' + url, | |
params=kwargs) | |
return r.json or r.text | |
class Application(object): | |
""" Helper class to get the Graph work. | |
Should be mostly used for obtaining short living user access_token. """ | |
@classmethod | |
def get_token(cls): | |
""" Returns application access token. | |
>>> len(Application.get_token()) > 0 | |
True | |
""" | |
r = do_request('oauth/access_token', | |
client_id=APP_ID, | |
client_secret=APP_SECRET, | |
grant_type='client_credentials') | |
return r.split('=')[1] | |
@classmethod | |
def get_users(cls): | |
""" Returns test user list. | |
>>> len(Application.get_users()) > 0 | |
True | |
""" | |
app_token = APP_ACCESS_TOKEN or cls.get_token() | |
return do_request(APP_ID + '/accounts/test-users', | |
access_token=app_token)['data'] | |
@classmethod | |
def create_user(cls, user_name='Vasya Pupkin'): | |
""" Creates test user with a given full name. | |
>>> len(Application.create_user()['access_token']) > 32 | |
True | |
""" | |
app_token = APP_ACCESS_TOKEN or cls.get_token() | |
return do_request(APP_ID + '/accounts/test-users', | |
installed='true', name=user_name, | |
locale='en_US', permissions='read_stream', | |
method='post', access_token=app_token) | |
@classmethod | |
def get_user_token(cls): | |
""" Returns acess roken of a 'first' user in the list. | |
NOTE: a test user access_token lives ~ 4 hours. | |
>>> len(Application.get_user_token()) > 32 | |
True | |
""" | |
return cls.get_users()[0]['access_token'] | |
class Graph(object): | |
""" Simple Facebook Graph wrapper. """ | |
def __init__(self): | |
self.access_token = Application.get_user_token() | |
def request(self, url, **kwargs): | |
""" Does Facebook Graph API request with test user access_token. | |
>>> g = Graph() | |
>>> g.request('search', q='Thievery Corporation', type='page')['data'][0]['name'] | |
u'Thievery Corporation' | |
""" | |
return do_request(url, access_token = self.access_token, **kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment