Google Analytics Graphs to your Dashboard in Python Web Frameworks

E-commerce solution providers like OpenCart, Magento Provide extensions to see Google analytics data in their own dashboards as graphs. whereas there are no such plugins available in Python. In this tutorial, we will learn how to display google graphs on your website.

Open Google Developers Console, Create a new project or open existing project. enable google analytics API. create a service account and generate a JSON Key File. Use the below function to generate an access token for analytics in read-only mode.

Python:

from oauth2client.client import SignedJwtAssertionCredentials
import json

def get_access_token():
    ''' Get Access Token From GOOGLE'''
    SCOPE = 'https://www.googleapis.com/auth/analytics.readonly'
    KEY_FILEPATH = <location to key file>
    with open(KEY_FILEPATH) as key_file:
        key_data = json.load(key_file)
    credentials = SignedJwtAssertionCredentials(
        key_data['client_email'], key_data['private_key'], SCOPE)
    return credentials.get_access_token().access_token

you need to pass Google UserID and Google Acess Token to template. 

Javascript:

//script to load analytics
<script>
(function(w,d,s,g,js,fs){
  g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
  js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
  js.src='https://apis.google.com/js/platform.js';
  fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
}(window,document,'script'));
</script>

//script to show graphs
<script>
gapi.analytics.ready(function() {

  gapi.analytics.auth.authorize({
    'serverAuth': {
      'access_token': "{{google_access_token}}"
    }
  });

  var dataChart1 = new gapi.analytics.googleCharts.DataChart({
    query: {
      'ids': '{{google_userid}}',
      'start-date': '30daysAgo',
      'end-date': 'today',
      'metrics': 'ga:sessions',
      'dimensions': 'ga:date',
      'sort': '-ga:date'
    },
    chart: {
      'container': 'chart-1-container',
      'type': 'LINE',
      'options': {
        'width': '100%'
      }
    }
  });
  dataChart1.execute();

//To change when selectbox value is changed

$("#chart-1").change(function(){
  dataChart1.set({query: {"start-date": $("#chart-1").val()}, chart:{"type":$("#chart-type-1").val()}})
  dataChart1.execute();
})
$("#chart-type-1").change(function(){
  dataChart1.set({query: {"start-date": $("#chart-1").val()}, chart:{"type":$("#chart-type-1").val()}})
  dataChart1.execute();
})
});
</script>

HTML

<div class='col-md-12 graph_wrap'>
<span>Users Sessions</span>
# select box to change type of graph
<span class="col-md-4 select_box">
  <select id="chart-type-1">
    <option value="LINE">Line</option>
    <option value="COLUMN">Column</option>
    <option value="TABLE">Table</option>
  </select>
</span>
# select box to switch between 1 week and 1 month 
<span class="col-md-4 select_box"> 
  <select id="chart-1">
    <option value="30daysAgo">Last 30 Days</option>
    <option value="7daysAgo">Last 7 Days</option>
  </select>
</span>
<div class="clearfix"></div>
<div id="chart-1-container"></div>

With above code you will generate the user session graph which can switch between week view and month view and also change type of Graph 

Other configuration options like dimensions,metrics and filters are available at Google Metrics Explorer.

Posted On 05 November 2015 By MicroPyramid


Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Event Delegation in Jquery

Event handling is the basic need to develop Rich Internet Web Applications and that will become very tough with elements added to DOM dynamically. Jquery ...

Continue Reading...
jQuery mouse events and touch events

jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler ...

Continue Reading...
How to drag and drop multiple files using Dropzone.js

Dropzone is a free open source library which makes a HTML element as dropzone, which enables user to drag files on to that area and ...

Continue Reading...
open source packages

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties