Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Fetch Page View Data from Google Analytics
import os
import json
import httplib2
import flask
from oauth2client import client
from apiclient.discovery import build
http_auth = None
view_id = '00000000' # Add view id here
app = flask.Flask(__name__)
def oauth2callback():
client_secrets = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'client_secrets.json')
flow = client.flow_from_clientsecrets(
redirect_uri=flask.url_for('oauth2callback', _external=True))
if 'code' not in flask.request.args:
auth_uri = flow.step1_get_authorize_url()
return flask.redirect(auth_uri)
auth_code = flask.request.args.get('code')
credentials = flow.step2_exchange(auth_code)
flask.session['credentials'] = credentials.to_json() #credentials.authorize(httplib2.Http())
return flask.redirect(flask.url_for('index'))
def index():
if 'credentials' not in flask.session:
return flask.redirect(flask.url_for('oauth2callback'))
credentials = client.OAuth2Credentials.from_json(flask.session['credentials'])
if credentials.access_token_expired:
return flask.redirect(flask.url_for('oauth2callback'))
http_auth = credentials.authorize(httplib2.Http(disable_ssl_certificate_validation=True))
analytics_service = build('analytics', 'v4', http_auth)
reports = analytics_service.reports()
response = reports.batchGet(body={
"viewId": view_id,
"dimensions": [{"name": "ga:date"}],
"dimensionFilterClauses": [{
"filters": [{
"dimensionName": "ga:pagePath",
"expressions": [
import pdb; pdb.set_trace()
if __name__ == '__main__':
import uuid
app.secret_key = str(uuid.uuid4()), host='', port=8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.