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
Setting up reactjs environment & first reactjs app(hello-world)

create your first react application hello-world from scratch. A step by step guide to understand and setup the reactjs environment. Understand the node package manager …

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...
How to use jQuery mobile touch events

JQuery mobile touch events - Event is nothing but all possible and different actions of visitors that a webpage can respond to. We have the …

Continue Reading...
Copy Text to ClipBoard event using Javascript

Here you can learn about copy to clipboard using JavaScript. Copying content from a web form without needing to use the default browser functions. For …

Continue Reading...
Using CasperJS to scrape website data

CasperJS can be used for Navigation Scipting, Scraping and testing. In this Tutorial we will see how to scrape data from website using CasperJS and …

Continue Reading...
Google Analytics Graphs to your Dashboard in Python Web Frameworks

Ecommerce solution providers like OpenCart, Magento Provide extensions to see Google analytics data in their own dashboards as graphs. whereas there are no such plugins …

Continue Reading...
Tracking your Product Sales, Views and Searches with Google Enhanced E-commerce Analytics

Enhanced E-commerce helps improving tracking of an ecommerce website. It gives Statistics in variable measurements. It is not be used alongside analytics plugin, as this …

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...
Image Cropping in Jquery (with Jcrop)

We are having many image cropping plugins developed in jquery that are being used to crop an image. Jcrop is one of the plugins developed …

Continue Reading...
Get tweets with Twitter API Javascript

Due to change in twitter API, its been hard to get tweets from twitter to your site using javascript. We got new API version 1.1 …

Continue Reading...
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...

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