How to get Google Analytics data in your Django or Python application?

Hi Friends,

Almost I’ve spent half a day for getting ‘Google Analytics’ data to my Django application. It is very easy. There are couple of packages available over the web. Here, I’m going to focus on ‘gdata’.

Step1: Install ‘gdata’ package

sudo easy_install gdata

Step2:

If you are planning to implement GA data on you personal application, this is the right way to follow. First, build ‘client’ then get data feed.

import gdata
from gdata.analytics import client

PROJECT_NAME = 'Your Project Name'

def get_ga_client(sdate, edate, metrics, dimensions):
     my_client = gdata.analytics.client.AnalyticsClient(source=PROJECT_NAME)
     my_client.client_login(
                            'USERNAME', # Your google account
                            'PASSWORD',
                            source=PROJECT_NAME,
                            service=my_client.auth_service,
                            account_type = 'GOOGLE',
                            )

     account_query = gdata.analytics.client.AccountFeedQuery()
     data_query = gdata.analytics.client.DataFeedQuery({
                                                        'ids': 'ga:YOUR PROFILE ID',
                                                        'metrics': metrics,
                                                        'dimensions': dimensions,
                                                        'start-date': sdate,
                                                        'end-date': edate,
                                                        })

     feed = my_client.GetDataFeed(data_query)
     return feed

def get_ga_data(sdate, edate, metrics, dimensions):
     result = []
     feed = get_ga_client(sdate, edate, metrics, dimensions)
     for value in feed.entry:
          for dimension, metric in zip(value.dimension, value.metric):
               result.append((dimension.value, metric.value))
     return result

PROJECT_NAME is the name of the application that makes the request. You can set it to anything you like.

Use your google account’s USERNAME and PASSWORD.

Step3:

Call get_ga_data(‘2013-07-01′, ‘2013-07-31′, ‘ga:visits’, ‘ga:visitorType’) in your application.

Step4:

[('New Visitor', '10347'), ('Returning Visitor', '22802')]

 


Django-Python Web based application developer.

Share This Post

Related Articles

Leave a Reply

© 2017 Techy Diary. All rights reserved.
Powered by Charvi Groups