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:
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.
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).
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 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)