Skip to content

Marina Mele's site

Reflections on family, values, and personal growth

Menu
  • Home
  • About
Menu

Use the Google Analytics API with Django

Posted on November 17, 2014November 13, 2014 by Marina Mele

Google Analytics is a powerful tool that gives you useful insight about the traffic that arrives in your website. But together with Django, you will be able to retrieve data of your Analytics account and display it to the user, on demand.

In this post you’ll learn how to put together Django, the oauth2 protocol and the Google Analytics API.

Let’s Start! 🙂

First of all, you might want to check this post if you’re not familiar with the Google Analytics API with Python.

Moreover, it assumes that you are familiar with Python and pip, and that you know Django and have a working application. If you navigate into the Python and Django sections of this website you’ll learn more about those 😉

Create a Google Application

I assume you have a working Django application, and that you want to extract data from your Google Analytics account using an existing Project. If you didn’t create a Project in the Google Developers Console, check this post and create one. Then, come back 😉

But if you have a live Django project, then you need to create a Web application instead. You just need to select Web application as the Application type when you are creating a Client Id in the Credentials section:

Google Web Application

 

In Authorized Javascript origins insert your website domain, and in authorized redirect uris, insert your domain plus /oauth2/oauth2callback. This endpoint will be used by django to catch the oatuh2 response.

After that, you should have the Oauth credentials in a json format.

From where should I get the JSON Credential file?

You can obtain it from the Google Developers Console. Go to your project and then select APIs & Oauth credentials –> Oauth and click on Download JSON.

Install oauth2 and Google Analytics

Next, we need to install the oaut2client python package. Activate your virtual environment (if you have one) and type:

$ pip install oauth2client

This will install oauth2client and the following packages: httplib2 (an http library), pyasn1 and pyasn1-modules (to use the ASN.1 protocol), and rsa to use the RSA cryptosystem).

No virtual environment?

Learn how to create one here, for Python 2.7 and for Python 3. It’s really useful, once you start using them you won’t stop! 🙂

Don’t forget to add these packages into the requirements file of your virtual environment.

And also, we will need the API Python Client library:

$ pip install python-gflags
$ pip install -U google-api-python-client

Create a Django App

Next, we will create a Django app to manage the Authorization process. Depending on where you want to create the app’s folder, you will run a slightly different command (this one will create the folder in the current directory):

$ python manage.py startapp oauth2_authentication

Take the client_secrets.json file and save it inside this app, and include this app into your settings.py file, in the INSTALLED_APPS.

Now that we have the app created, we are going to create two different models that will store the Flow and Credential objects.

Edit the models.py inside the oaut2_authentication app and write:

from django.db import models
from django.contrib.auth.models import User
from oauth2client.django_orm import FlowField, CredentialsField


class FlowModel(models.Model):
    id = models.ForeignKey(User, primary_key=True)
    flow = FlowField()


class CredentialsModel(models.Model):
    id = models.ForeignKey(User, primary_key=True)
    credential = CredentialsField()

Next, we’ll edit the urls of your app. First, open the main urls.py and add the following urlpattern:

url(r'^oauth2/', include('oauth2_authentication.urls', namespace="oauth2"))

And in the oauth2_authentication/urls.py write:

from django.conf.urls import patterns, url
from . import views

urlpatterns = patterns(
    '',
    url(r'^$', views.index, name='index'),
    url(r'oauth2callback', views.auth_return, name='return'),
)

This way, /oauth2 will start the authorization process, and /oauth2/oaut2callback will wait for the authorization response.

But we need to write our views.py first:

import os
import httplib2
from oauth2client import xsrfutil
from oauth2client.client import flow_from_clientsecrets
from oauth2client.django_orm import Storage

from apiclient.discovery import build

from django.contrib.auth.decorators import login_required
from django.http import HttpResponseBadRequest
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.urlresolvers import reverse
from django.contrib.sites.models import get_current_site

from .models import CredentialsModel, FlowModel

CLIENT_SECRETS = os.path.join(
    os.path.dirname(__file__), 'client_secrets.json')


def get_accounts_ids(service):
    accounts = service.management().accounts().list().execute()
    ids = []
    if accounts.get('items'):
        for account in accounts['items']:
            ids.append(account['id'])
    return ids


@login_required
def index(request):
    # use the first REDIRECT_URI if you are developing your app
    # locally, and the second in production
    # REDIRECT_URI = 'http://localhost:8000/oauth2/oauth2callback'
    REDIRECT_URI = "https://%s%s" % (
        get_current_site(request).domain, reverse("oauth2:return"))
    FLOW = flow_from_clientsecrets(
        CLIENT_SECRETS,
        scope='https://www.googleapis.com/auth/analytics.readonly',
        redirect_uri=REDIRECT_URI
    )
    user = request.user
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    credential = storage.get()
    if credential is None or credential.invalid is True:
        FLOW.params['state'] = xsrfutil.generate_token(
            settings.SECRET_KEY, user)
        authorize_url = FLOW.step1_get_authorize_url()
        f = FlowModel(id=user, flow=FLOW)
        f.save()
        return HttpResponseRedirect(authorize_url)
    else:
        http = httplib2.Http()
        http = credential.authorize(http)
        service = build('analytics', 'v3', http=http)
        ids = get_account_ids(service)
        return render(
            request, 'oauth2_authentication/main.html', {'ids':ids})


@login_required
def auth_return(request):
    user = request.user
    if not xsrfutil.validate_token(
            settings.SECRET_KEY, request.REQUEST['state'], user):
        return HttpResponseBadRequest()
    FLOW = FlowModel.objects.get(id=user).flow
    credential = FLOW.step2_exchange(request.REQUEST)
    storage = Storage(CredentialsModel, 'id', user, 'credential')
    storage.put(credential)
    return HttpResponseRedirect("/oauth2")

Note that you have to choose which REDIRECT_URI to use, depending on if you are developing your Django app locally or your app is live on a server.

Inside the FLOW object, we have used the readonly scope, but you could also choose:

https://www.googleapis.com/auth/analytics for writing permissions, and https://www.googleapis.com/auth/analytics.manage.users to view and manage permission of users in the Analytics accounts (more info).

And finally, write something in the oauth2_authentication/main.html template, like:

Your credentials are up to date! :-)

{% if ids %}
The List of Ids of your Google Analytics accounts are: {{ids}}
{% endif %}

Now you just need to start the server and visit /oauth2 to start the authentication process. If everything worked correctly, you should see the list of ids of your Google Analytics account.

Note that once you have the Google Analytics service object you can retrieve all the data you want from your accounts. To see more examples, you can check this post: Google Analytics API with Python.

Marina Melé
Marina Mele

Marina Mele has experience in artificial intelligence implementation and has led tech teams for over a decade. On her personal blog (marinamele.com), she writes about personal growth, family values, AI, and other topics she’s passionate about. Marina also publishes a weekly AI newsletter featuring the latest advancements and innovations in the field (marinamele.substack.com)

Categories

  • Personal Growth and Development
  • Artificial Intelligence
  • Mindful Parenting and Family Life
  • Productivity and Time Management
  • Mindfulness and Wellness
  • Values and Life Lessons
  • Posts en català
  • Other things to learn

Recent Posts

  • Understanding Frustration in Children
  • What is ChatGPT and how it compares to Bard and Claude
  • BlueSky Social – A Sneak Peek at the Future of Social Media
  • The Incredible Journey of AI Image Generation
  • AI and Fundamental Rights: How the AI Act Aims to Protect Individuals

RSS

  • Entries RSS
Follow @marina_mele
  • Cookie Policy
  • Privacy Policy
©2025 Marina Mele's site | Built using WordPress and Responsive Blogily theme by Superb
This website uses cookies to improve your experience. If you keep navigating through this website, we'll assume you're ok with this, but you can opt-out if you wish.Accept Read More
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT