Skip to content

Instantly share code, notes, and snippets.

@debrouwere
Created August 16, 2014 08:56
Show Gist options
  • Save debrouwere/b349743c21236a305392 to your computer and use it in GitHub Desktop.
Save debrouwere/b349743c21236a305392 to your computer and use it in GitHub Desktop.
Access Google Analytics data with rauth in Python
import os
import json
from flask import Flask, request, redirect, jsonify
from rauth import OAuth2Service
GOOGLE_AUTH_URI = 'https://accounts.google.com/o/oauth2/auth'
GOOGLE_REVOKE_URI = 'https://accounts.google.com/o/oauth2/revoke'
GOOGLE_TOKEN_URI = 'https://accounts.google.com/o/oauth2/token'
GOOGLE_ANALYTICS_API_ENDPOINT = 'https://www.googleapis.com/analytics/v3/'
google = OAuth2Service(
name='google',
client_id=os.environ['GOOGLE_ANALYTICS_CLIENT_ID'],
client_secret=os.environ['GOOGLE_ANALYTICS_CLIENT_SECRET'],
access_token_url=GOOGLE_TOKEN_URI,
authorize_url=GOOGLE_AUTH_URI,
base_url=GOOGLE_ANALYTICS_API_ENDPOINT)
REDIRECT_URI = 'http://localhost:5000/auth/google/callback'
app = Flask(__name__)
@app.route('/auth/google')
def authorization():
params = {
'scope': 'https://www.googleapis.com/auth/analytics.readonly',
'access_type': 'offline',
'response_type': 'code',
'redirect_uri': REDIRECT_URI,
}
authorize_url = google.get_authorize_url(**params)
return redirect(authorize_url)
@app.route('/auth/google/callback')
def callback():
credentials = google.get_access_token(data={
'code': request.args['code'],
'grant_type': 'authorization_code',
'redirect_uri': REDIRECT_URI
}, decoder=json.loads)
"""
# or instead, create a session right away
session = google.get_auth_session(data={
'code': request.args['code'],
'grant_type': 'authorization_code',
'redirect_uri': REDIRECT_URI
})
print session.get('management/accountSummaries').json()
"""
return jsonify(refresh_token=credentials)
app.run(debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment