Skip to content

Instantly share code, notes, and snippets.

Embed
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__)
@app.route('/oauth2callback')
def oauth2callback():
client_secrets = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'client_secrets.json')
flow = client.flow_from_clientsecrets(
client_secrets,
scope='https://www.googleapis.com/auth/analytics.readonly',
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)
else:
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'))
@app.route('/')
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'))
else:
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={
"reportRequests":[
{
"viewId": view_id,
"dateRanges":[
{
"startDate":"30daysAgo",
"endDate":"today"
}],
"metrics":[
{
"expression":"ga:pageviews"
}],
"dimensions": [{"name": "ga:date"}],
"dimensionFilterClauses": [{
"filters": [{
"dimensionName": "ga:pagePath",
"expressions": [
"/create-account"
]
}]
}]
}]
}).execute()
import pdb; pdb.set_trace()
if __name__ == '__main__':
import uuid
app.secret_key = str(uuid.uuid4())
app.run(debug=True, host='0.0.0.0', 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.