Innovate anywhere, anytime withruncode.io Your cloud-based dev studio.
JavaScript

Google Analytics Graphs to your Dashboard in Python Web Frameworks

2022-07-20

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.