Browse Source

Merge pull request #76 from CatalystCode/feature/configurable-google-analytics

Feature/Make client-side analytics configurable
pull/73/head
Hiroki Nakayama 5 years ago
committed by GitHub
parent
commit
97b435d4dc
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 120 additions and 37 deletions
  1. 2
      Dockerfile
  2. 10
      app/app/settings.py
  3. 11
      app/server/templates/base.html
  4. 14
      app/server/templates/tags/azure_appinsights.html
  5. 10
      app/server/templates/tags/google_analytics.html
  6. 0
      app/server/templatetags/__init__.py
  7. 18
      app/server/templatetags/analytics.py
  8. 91
      azuredeploy.json
  9. 1
      requirements.txt

2
Dockerfile

@ -13,6 +13,8 @@ ENV DEBUG="True"
ENV SECRET_KEY="change-me-in-production" ENV SECRET_KEY="change-me-in-production"
ENV BIND="0.0.0.0:80" ENV BIND="0.0.0.0:80"
ENV WORKERS="2" ENV WORKERS="2"
ENV GOOGLE_TRACKING_ID=""
ENV AZURE_APPINSIGHTS_IKEY=""
EXPOSE 80 EXPOSE 80

10
app/app/settings.py

@ -64,6 +64,7 @@ MIDDLEWARE = [
'django.contrib.messages.middleware.MessageMiddleware', 'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware',
'applicationinsights.django.ApplicationInsightsMiddleware',
] ]
ROOT_URLCONF = 'app.urls' ROOT_URLCONF = 'app.urls'
@ -82,6 +83,9 @@ TEMPLATES = [
'social_django.context_processors.backends', 'social_django.context_processors.backends',
'social_django.context_processors.login_redirect', 'social_django.context_processors.login_redirect',
], ],
'libraries': {
'analytics': 'server.templatetags.analytics',
},
}, },
}, },
] ]
@ -185,4 +189,10 @@ SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# on the import phase # on the import phase
IMPORT_BATCH_SIZE = 500 IMPORT_BATCH_SIZE = 500
GOOGLE_TRACKING_ID = os.getenv('GOOGLE_TRACKING_ID', 'UA-125643874-2')
APPLICATION_INSIGHTS = {
'ikey': os.getenv('AZURE_APPINSIGHTS_IKEY'),
}
django_heroku.settings(locals(), test_runner=False) django_heroku.settings(locals(), test_runner=False)

11
app/server/templates/base.html

@ -1,15 +1,9 @@
{% load static %} {% load static %}
{% load analytics %}
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-125643874-2"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-125643874-2');
</script>
{% google_analytics %}
<meta charset="utf-8"> <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
@ -41,6 +35,7 @@
<meta name="msapplication-TileImage" content="{% static 'images/favicons/ms-icon-144x144.png' %}"> <meta name="msapplication-TileImage" content="{% static 'images/favicons/ms-icon-144x144.png' %}">
<meta name="theme-color" content="#ffffff"> <meta name="theme-color" content="#ffffff">
{% block header %}{% endblock %} {% block header %}{% endblock %}
{% azure_appinsights %}
</head> </head>
<body> <body>

14
app/server/templates/tags/azure_appinsights.html

@ -0,0 +1,14 @@
{# See https://apmtips.com/blog/2015/03/18/javascript-snippet-explained/ #}
{% if azure_appinsights_ikey %}
<script type="text/javascript">
var appInsights=window.appInsights||function(a){
function b(a){c[a]=function(){var b=arguments;c.queue.push(function(){c[a].apply(c,b)})}}var c={config:a},d=document,e=window;setTimeout(function(){var b=d.createElement("script");b.src=a.url||"https://az416426.vo.msecnd.net/scripts/a/ai.0.js",d.getElementsByTagName("script")[0].parentNode.appendChild(b)});try{c.cookie=d.cookie}catch(a){}c.queue=[];for(var f=["Event","Exception","Metric","PageView","Trace","Dependency"];f.length;)b("track"+f.pop());if(b("setAuthenticatedUserContext"),b("clearAuthenticatedUserContext"),b("startTrackEvent"),b("stopTrackEvent"),b("startTrackPage"),b("stopTrackPage"),b("flush"),!a.disableExceptionTracking){f="onerror",b("_"+f);var g=e[f];e[f]=function(a,b,d,e,h){var i=g&&g(a,b,d,e,h);return!0!==i&&c["_"+f](a,b,d,e,h),i}}return c
}({
{% if DEBUG %}
enableDebug: true,
{% endif %}
instrumentationKey: "{{ azure_appinsights_ikey }}"
});
window.appInsights=appInsights,appInsights.queue&&0===appInsights.queue.length&&appInsights.trackPageView();
</script>
{% endif %}

10
app/server/templates/tags/google_analytics.html

@ -0,0 +1,10 @@
{% if google_tracking_id %}
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id={{ google_tracking_id }}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag("js", new Date());
gtag("config", "{{ google_tracking_id }}");
</script>
{% endif %}

0
app/server/templatetags/__init__.py

18
app/server/templatetags/analytics.py

@ -0,0 +1,18 @@
from django import template
from app import settings
register = template.Library()
@register.inclusion_tag('tags/google_analytics.html')
def google_analytics():
return {'google_tracking_id': settings.GOOGLE_TRACKING_ID}
@register.inclusion_tag('tags/azure_appinsights.html')
def azure_appinsights():
return {
'DEBUG': settings.DEBUG,
'azure_appinsights_ikey': settings.APPLICATION_INSIGHTS['ikey'],
}

91
azuredeploy.json

@ -2,35 +2,35 @@
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#", "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0", "contentVersion": "1.0.0.0",
"parameters": { "parameters": {
"appName":{
"appName": {
"type": "string", "type": "string",
"minLength": 1,
"minLength": 1,
"metadata": { "metadata": {
"description": "The name for the webapp. Must be globally unique." "description": "The name for the webapp. Must be globally unique."
} }
}, },
"secretKey":{
"secretKey": {
"type": "securestring", "type": "securestring",
"minLength": 16,
"minLength": 16,
"metadata": { "metadata": {
"description": "The value to use as the Django secret key." "description": "The value to use as the Django secret key."
} }
}, },
"adminUserName":{
"adminUserName": {
"type": "string", "type": "string",
"minLength": 1,
"minLength": 1,
"metadata": { "metadata": {
"description": "The user name for the admin account." "description": "The user name for the admin account."
} }
}, },
"adminContactEmail":{
"adminContactEmail": {
"type": "string", "type": "string",
"minLength": 1,
"minLength": 1,
"metadata": { "metadata": {
"description": "The contact email address for the admin account." "description": "The contact email address for the admin account."
} }
}, },
"adminPassword":{
"adminPassword": {
"type": "securestring", "type": "securestring",
"minLength": 16, "minLength": 16,
"metadata": { "metadata": {
@ -102,26 +102,20 @@
"databaseServerName": "[concat(parameters('appName'),'-state')]", "databaseServerName": "[concat(parameters('appName'),'-state')]",
"setupScriptName": "[concat(parameters('appName'),'-setup')]", "setupScriptName": "[concat(parameters('appName'),'-setup')]",
"appServicePlanName": "[concat(parameters('appName'),'-hosting')]", "appServicePlanName": "[concat(parameters('appName'),'-hosting')]",
"env": [
{
"name": "WEBSITES_ENABLE_APP_SERVICE_STORAGE",
"value": "false"
},
{
"name": "DEBUG",
"value": "False"
},
{
"name": "SECRET_KEY",
"value": "[parameters('secretKey')]"
},
{
"name": "DATABASE_URL",
"value": "[variables('databaseConnectionString')]"
}
]
"analyticsName": "[concat(parameters('appName'),'-analytics')]"
}, },
"resources": [ "resources": [
{
"type": "Microsoft.Insights/components",
"apiVersion": "2015-05-01",
"name": "[variables('analyticsName')]",
"location": "[variables('location')]",
"tags": {},
"kind": "web",
"properties": {
"Application_Type": "web"
}
},
{ {
"apiVersion": "2017-08-01", "apiVersion": "2017-08-01",
"type": "Microsoft.Web/serverfarms", "type": "Microsoft.Web/serverfarms",
@ -199,7 +193,20 @@
"[parameters('adminContactEmail')]", "[parameters('adminContactEmail')]",
"[parameters('adminPassword')]" "[parameters('adminPassword')]"
], ],
"environmentVariables": "[variables('env')]",
"environmentVariables": [
{
"name": "DEBUG",
"value": "False"
},
{
"name": "SECRET_KEY",
"value": "[parameters('secretKey')]"
},
{
"name": "DATABASE_URL",
"value": "[variables('databaseConnectionString')]"
}
],
"resources": { "resources": {
"requests": { "requests": {
"cpu": "1", "cpu": "1",
@ -224,6 +231,7 @@
"location": "[variables('location')]", "location": "[variables('location')]",
"dependsOn": [ "dependsOn": [
"[resourceId('Microsoft.DBforPostgreSQL/servers/', variables('databaseServerName'))]", "[resourceId('Microsoft.DBforPostgreSQL/servers/', variables('databaseServerName'))]",
"[resourceId('Microsoft.Insights/components', variables('analyticsName'))]",
"[resourceId('Microsoft.Web/serverfarms', variables('appServicePlanName'))]" "[resourceId('Microsoft.Web/serverfarms', variables('appServicePlanName'))]"
], ],
"properties": { "properties": {
@ -231,7 +239,32 @@
"siteConfig": { "siteConfig": {
"linuxFxVersion": "[concat('DOCKER|', parameters('dockerImageName'))]", "linuxFxVersion": "[concat('DOCKER|', parameters('dockerImageName'))]",
"alwaysOn": true, "alwaysOn": true,
"appSettings": "[variables('env')]"
"appSettings": [
{
"name": "WEBSITES_ENABLE_APP_SERVICE_STORAGE",
"value": "false"
},
{
"name": "AZURE_APPINSIGHTS_IKEY",
"value": "[reference(resourceId('Microsoft.Insights/components', variables('analyticsName')), '2014-04-01').InstrumentationKey]"
},
{
"name": "GOOGLE_TRACKING_ID",
"value": ""
},
{
"name": "DEBUG",
"value": "False"
},
{
"name": "SECRET_KEY",
"value": "[parameters('secretKey')]"
},
{
"name": "DATABASE_URL",
"value": "[variables('databaseConnectionString')]"
}
]
}, },
"serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('appServicePlanName'))]" "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', variables('appServicePlanName'))]"
} }

1
requirements.txt

@ -1,3 +1,4 @@
applicationinsights==0.11.7
dj-database-url==0.5.0 dj-database-url==0.5.0
Django==2.1.5 Django==2.1.5
django-filter==2.0.0 django-filter==2.0.0

Loading…
Cancel
Save