使用 Django 部署 Google Analytics [英] Deploying Google Analytics With Django
问题描述
我们即将部署一个新的 Django 网站,我们想使用 Google Analytics 来跟踪网站上的流量.但是,我们不希望开发实例上的所有点击都对 Google Analytics(分析)统计数据做出贡献.
We're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics.
有几种方法可以解决这个问题:
There are a few ways we could deal with this:
- 在 settings.py 中有一个配置选项,基本模板使用它来决定是否包含适当的
元素,
- 在部署到生产服务器之前维护一个我们拉入的分支,我们确保它包含
元素,
- 使用 Google Analytics 做一些事情来阻止对 127.0.0.1 或 localhost 的点击,或者
- 别的东西.
第一个选项似乎是最明智的,但我不确定是否如此.例如,我们是否必须开始将 google_analytics
变量传递到我们所有的视图中?
The first option seems the most sensible, but I'm not sure if it is. For example, would we have to start passing a google_analytics
variable into all of our views?
你有什么想法?
推荐答案
首先,创建一种方法让您的开发和生产服务器从不同的文件中提取设置,比如 dev.py 和 prod.py.有很多方法可以做到这一点.
First, create a way to have your development and production servers pull settings from different files, say dev.py and prod.py. There are lots of ways to do this.
然后,创建一个设置,GOOGLE_ANALYTICS_KEY
.在 dev.py 中将其设置为空字符串.在 prod.py 中,将其设置为您的密钥,例如UA-124465-1".创建一个上下文处理器将此设置添加到您的所有模板上下文中,或者作为 GOOGLE_ANALYTICS_KEY
,或者只是继续添加您的设置模块.然后,在您的模板中,使用它有条件地包含您的分析代码:
Then, create a setting, GOOGLE_ANALYTICS_KEY
. In dev.py set it to the empty string. In prod.py, set it to your key, something like "UA-124465-1". Create a context processor to add this setting to all your template contexts, either as GOOGLE_ANALYTICS_KEY
, or just go ahead and add your settings module. Then, in your template, use it to conditionally include your analytics code:
{% if settings.GOOGLE_ANALYTICS_KEY %}
<script> blah blah {{settings.GOOGLE_ANALYTICS_KEY}} blah blah </script>
{% endif %}
这篇关于使用 Django 部署 Google Analytics的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!