python 使用 Django 部署 Google Analytics
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/629696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Deploying Google Analytics With Django
提问by Daniel Watkins
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.
我们即将部署一个新的 Django 网站,我们想使用 Google Analytics 来跟踪网站上的流量。但是,我们不希望开发实例上的所有点击都对 Google Analytics 统计数据做出贡献。
There are a few ways we could deal with this:
我们可以通过以下几种方式来处理:
- have a configuration option in settings.py which the base template uses to decide whether or not to include the appropriate
<script>
elements, - maintain a branch which we pull into before deploying to the production server, which we ensure includes the
<script>
elements, - do something with Google Analytics to block hits to 127.0.0.1 or localhost, or
- something else.
- 在 settings.py 中有一个配置选项,基本模板使用它来决定是否包含适当的
<script>
元素, - 在部署到生产服务器之前维护一个我们拉入的分支,我们确保其中包含
<script>
元素, - 用 Google Analytics 做一些事情来阻止对 127.0.0.1 或 localhost 的点击,或者
- 别的东西。
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?
第一个选项似乎是最明智的,但我不确定它是否如此。例如,我们是否必须开始将一个google_analytics
变量传递到我们所有的视图中?
What are your thoughts?
你觉得呢?你有没有什么想法?
回答by Ned Batchelder
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.
首先,创建一种方法让您的开发和生产服务器从不同的文件中提取设置,比如 dev.py 和 prod.py。有很多方法可以做到这一点。
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 processorto 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:
然后,创建一个设置,GOOGLE_ANALYTICS_KEY
。在 dev.py 中将其设置为空字符串。在 prod.py 中,将其设置为您的密钥,例如“UA-124465-1”。创建一个上下文处理器以将此设置添加到您的所有模板上下文中,或者作为GOOGLE_ANALYTICS_KEY
,或者继续添加您的设置模块。然后,在您的模板中,使用它有条件地包含您的分析代码:
{% if settings.GOOGLE_ANALYTICS_KEY %}
<script> blah blah {{settings.GOOGLE_ANALYTICS_KEY}} blah blah </script>
{% endif %}
回答by mikl
A little late to the party, but there's a reusable Django app called django-google-analytics. The easiest way to use it is:
聚会有点晚了,但有一个可重用的 Django 应用程序,名为django-google-analytics。最简单的使用方法是:
- Add the
google_analytics
application to yourINSTALLED_APPS
section of yoursettings.py
. - In your base template, usually a
base.html
, insert this tag at the very top:{% load analytics %}
- In the same template, insert the following code right before the closing body tag:
{% analytics "UA-xxxxxx-x" %}
theUA-xxxxxx-x
is a unique Google Analytics code for your domain.
- 将
google_analytics
应用程序添加到您INSTALLED_APPS
的settings.py
. - 在您的基本模板中,通常是 a
base.html
,在最顶部插入此标签:{% load analytics %}
- 在同一个模板中,在结束正文标记之前插入以下代码:
{% analytics "UA-xxxxxx-x" %}
这UA-xxxxxx-x
是您域的唯一 Google Analytics 代码。
回答by worksology
My solution takes a similar approach to Ned's preferred answer, but separates the analytics code into its own template. I prefer this, so I can just copy the template from project to project.
我的解决方案采用了与 Ned 的首选答案类似的方法,但将分析代码分成自己的模板。我更喜欢这个,所以我可以将模板从一个项目复制到另一个项目。
Here's a snippet from my context_processor file:
这是我的 context_processor 文件中的一个片段:
from django.conf import settings
from django.template.loader import render_to_string
def analytics(request):
"""
Returns analytics code.
"""
if not settings.DEBUG:
return { 'analytics_code': render_to_string("analytics/analytics.html", { 'google_analytics_key: settings.GOOGLE_ANALYTICS_KEY }) }
else:
return { 'analytics_code': "" }
Of course you'll need to tell Django to include this in your context. In in your settings.py file, include:
当然,您需要告诉 Django 将其包含在您的上下文中。在您的 settings.py 文件中,包括:
TEMPLATE_CONTEXT_PROCESSORS = (
...
"context_processors.analytics",
)
I have it set up to include the analytics code only when DEBUG is set to False, but you may prefer to key it off something else, perhaps a new setting altogether. I think DEBUG is a good default since it supposes you don't want to track any hits while debugging/developing.
我已将其设置为仅在 DEBUG 设置为 False 时包含分析代码,但您可能更喜欢将其关闭其他内容,也许完全是新设置。我认为 DEBUG 是一个很好的默认设置,因为它假设您不想在调试/开发时跟踪任何命中。
Create a setting with your Google Analytics Key:
使用您的 Google Analytics Key 创建一个设置:
GOOGLE_ANALYTICS_KEY = "UA-1234567-8"
Create a template called: "analytics/analytics.html" that includes something like this:
创建一个名为“analytics/analytics.html”的模板,其中包含如下内容:
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("{{ google_analytics_key }}");
pageTracker._trackPageview();
} catch(err) {}</script>
Finally, just before the closing tag in your base.html template, add this:
最后,就在 base.html 模板中的结束标记之前,添加以下内容:
{{ analytics_code }}
Now your analytics code will be included only when DEBUG=False. Otherwise, nothing will be included.
现在,只有当 DEBUG=False 时才会包含您的分析代码。否则,将不包含任何内容。
回答by Mark Chackerian
All of these other solutions may work, but they are all overkill now because you can easily set up a filter in Google Analytics to filter out all traffic that is not coming from your production website or websites. See Create/Manage ProfileFilters in the GA Help. A solution with no code just makes everybody's life easier.
所有这些其他解决方案都可能有效,但现在它们都有些矫枉过正,因为您可以轻松地在 Google Analytics 中设置过滤器来过滤掉所有不是来自您的生产网站或网站的流量。请参阅GA 帮助中的创建/管理配置文件过滤器。没有代码的解决方案只会让每个人的生活更轻松。
Note: there are two caveats
注意:有两个警告
- this doesn't work with realtime filtering, because no filters are applied to realtime (as of July 2012--check their documents)
- you have to be an admin with the Google Analytics account to set this up
- 这不适用于实时过滤,因为没有过滤器应用于实时(截至 2012 年 7 月 - 检查他们的文档)
- 您必须是 Google Analytics(分析)帐户的管理员才能进行设置
回答by Chien-Wei Huang
Another simple way.
In settings.py
,Check debug
is True
, then add:
另一种简单的方法。在 中settings.py
,勾选debug
是True
,然后添加:
INTERNAL_IPS = (
'127.0.0.1',
'localhost',
)
Then you can use things in your template like this:
然后你可以在你的模板中使用这样的东西:
{% if not debug %}
<script> blah blah </script>
{% endif %}
If want to change to production, set debug
to False
.
如果要更改为生产,请设置debug
为False
。
回答by Andrew Wilkinson
I mostly agree with Ned, although I have a single setting called IS_LIVE_SITE which toggles analytics code, adverts and a few other things. This way I can keep all the keys in subversion (as it is a pain to look them up) and still toggle them on or off easily.
我主要同意 Ned,尽管我有一个名为 IS_LIVE_SITE 的设置,它可以切换分析代码、广告和其他一些东西。通过这种方式,我可以将所有键保持在颠覆状态(因为查找它们很痛苦)并且仍然可以轻松地打开或关闭它们。
回答by lacker
Instead of including the script tag directly in your html, just change the analytics javascript so it only runs if the href does not contain your prod site's name. This will work without any extra configuration.
不要直接在您的 html 中包含 script 标签,只需更改分析 javascript 以便它仅在 href 不包含您的 prod 站点名称时运行。这将在没有任何额外配置的情况下工作。
回答by S.Lott
You have template context processors that can be used to pass values to all templates without updating all your views.
您有模板上下文处理器,可用于将值传递给所有模板,而无需更新所有视图。
http://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
http://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors
回答by Ryan Walton
Here's the dead simple way that I solved it:
这是我解决它的简单方法:
Create an app in your project called 'utils' if you haven't already. See these directions.
如果您还没有,请在您的项目中创建一个名为“utils”的应用程序。请参阅这些说明。
However, follow this approach to include all global context processers in addition to the project settings. It's seems to be a better practice. Here are the instructions.
但是,请遵循此方法以包含除项目设置之外的所有全局上下文处理器。这似乎是一种更好的做法。这是说明。
So, after you create your 'utils' app, create a a file called context_processors.py in /utils that looks like this:
因此,在创建“utils”应用程序后,在 /utils 中创建一个名为 context_processors.py 的文件,如下所示:
from django.conf import settings
def googleanalytics(request):
return {
'google_tracking_id' : settings.GOOGLE_TRACKING_ID,
}
In you settings.py file, add this:
在 settings.py 文件中,添加以下内容:
import django.conf.global_settings as DEFAULT_SETTINGS
TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
'utils.context_processors.googleanalytics',
)
)
Hope this helps!
希望这可以帮助!
回答by Luca Giovenzana
Hi all it's a quite old post.. But since I spent some time in searching some reusable app that is still actively maintained I want to share what I found:
大家好,这是一个很老的帖子..但是因为我花了一些时间搜索一些仍在积极维护的可重用应用程序,所以我想分享我的发现:
https://github.com/jcassee/django-analytical
https://github.com/jcassee/django-analytical
This project is still actively maintained and does not require the ID to be added to the database (I think is better if you have one project per site) so it is bared in the code no matter if the environment is development or production.
这个项目还在积极维护中,不需要将ID添加到数据库中(我认为如果您每个站点一个项目更好),因此无论环境是开发还是生产环境,它都在代码中裸露。