Skip to content

Instantly share code, notes, and snippets.

@lrvick
Created January 28, 2015 09:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lrvick/f3794f2fbc37482afd1c to your computer and use it in GitHub Desktop.
Save lrvick/f3794f2fbc37482afd1c to your computer and use it in GitHub Desktop.
Flask / Python Facebook Graph oAuth Example
#!/usr/bin/python2.6
import os.path
import json
import urllib2
import urllib
import urlparse
import BaseHTTPServer
import webbrowser
APP_ID = '218248774869881'
APP_SECRET = '091d1c1501436f364699713a1ee714f5'
ENDPOINT = 'graph.facebook.com'
REDIRECT_URI = 'http://localhost:8080/'
ACCESS_TOKEN = None
LOCAL_FILE = '.fb_access_token'
STATUS_TEMPLATE = u"{name}\033[0m: {message}"
def get_url(path, args=None):
args = args or {}
if ACCESS_TOKEN:
args['access_token'] = ACCESS_TOKEN
if 'access_token' in args or 'client_secret' in args:
endpoint = "https://"+ENDPOINT
else:
endpoint = "http://"+ENDPOINT
return endpoint+path+'?'+urllib.urlencode(args)
def get(path, args=None):
return urllib2.urlopen(get_url(path, args=args)).read()
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
global ACCESS_TOKEN
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
code = urlparse.parse_qs(urlparse.urlparse(self.path).query).get('code')
code = code[0] if code else None
if code is None:
self.wfile.write("Sorry, authentication failed.")
sys.exit(1)
response = get('/oauth/access_token', {'client_id':APP_ID,
'redirect_uri':REDIRECT_URI,
'client_secret':APP_SECRET,
'code':code})
ACCESS_TOKEN = urlparse.parse_qs(response)['access_token'][0]
open(LOCAL_FILE,'w').write(ACCESS_TOKEN)
self.wfile.write("You have successfully logged in to facebook. "
"You can close this window now.")
def print_status(item, color=u'\033[1;35m'):
print color+STATUS_TEMPLATE.format(name=item['from']['name'],
message=item['message'].strip())
if __name__ == '__main__':
if not os.path.exists(LOCAL_FILE):
print "Logging you in to facebook..."
webbrowser.open(get_url('/oauth/authorize',
{'client_id':APP_ID,
'redirect_uri':REDIRECT_URI,
'scope':'offline_access,read_stream'}))
httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 8080), RequestHandler)
while ACCESS_TOKEN is None:
httpd.handle_request()
else:
ACCESS_TOKEN = open(LOCAL_FILE).read()
for item in json.loads(get('/me/feed'))['data']:
if item['type'] == 'status':
print_status(item)
if 'comments' in item:
for comment in item['comments']['data']:
print_status(comment, color=u'\033[1;33m')
print '---'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment