2011-08-18 24 views
7

我使用Django做一个电子邮件Django的像素追踪

像素Tracker是很容易从一个Django视图返回的实际图像(以及如何将这样做?),或者是更容易只是将重定向返回到实际图像所在的url?

回答

6

你并不需要一个实际的图像跟踪器像素。事实上,如果你没有一个更好。

只需使用视图作为源图像标签,并使其返回空白响应。

+0

做内容-I型此事作出回应? – MattoTodd

+0

是的,你应该可以把它做成image/png。 –

+5

为了记录,我注意到,发送空白响应可能会产生问题 - 至少在Chrome上的gmail上,会导致邮件中出现图像字形损坏。最好传播一个微不足道的图片,[如Russell Keith-Magee所建议](https://groups.google.com/forum/#!topic/django-users/-xiaSqXdWvc)。 –

2

的Django有一个static file帮手可以用来服务立形象,但不推荐,因为性能。我相信有一个观点,记录跟踪像素,然后重定向到一个网址,这将会给你最好的表现。

3

因为这是我的谷歌搜索的第一个结果,最好的答案是埋在丹尼尔的链接(但没有提到最好),我想我只是发布答案,所以没有人试图返回一个空白正如Michael所指出的那样,反应并不理想。

的解决方案是使用一个标准视图和与所述原始数据,构成了一个单一的像素的gif返回一个HttpResponse。不必击中磁盘或重定向是一个巨大的优势。

注意URL模式使用的跟踪代码作为图像名称,以便有url中没有明显?代码= jf8992jf。

from django.conf.urls import patterns, url 
from emails.views.pixel import PixelView 

urlpatterns = patterns('', 
    url(r'^/p/(?P<pixel>\w+).gif$', PixelView.as_view(), name='email_pixel'), 
) 

这里是视图。请注意,它使用cache_control来防止请求运行异常。 Firefox(以及许多电子邮件客户端)例如会每次请求图像两次,出于某种原因您可能不关心,但需要担心。通过添加max_age = 60,您将每分钟获得一个请求。

from django.views.decorators.cache import cache_control 
from django.http.response import HttpResponse 
from django.views.generic import View 

class PixelView(View): 

    @cache_control(must_revalidate=True, max_age=60) 
    def get(self, request, pixel): 
     """ 
     Tracking pixel for opening an email 
     :param request: WSGIRequest 
     :param pixel: str 
     :return: HttpResponse 
     """ 

     # Do whatever tracking you want here 

     # Render the pixel 
     pixel_image = b'\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\x00\x00\x00\x21\xf9\x04\x01\x00\x00\x00\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x44\x01\x00\x3b' 
     return HttpResponse(pixel_image, content_type='image/gif') 
+1

值得注意的是,在Python3中''pixel_image'应该是[前缀](https://docs.python.org/3/library/stdtypes.html#bytes)与'b',这样它的类型是'bytes'而不是'str'。否则,响应不会是实际的图像,并且仍然会导致Michael提到的破碎图像字形。 – alxs

+0

感谢您的更新@alxs - 我已更新示例代码以包含'b'。 – dotcomly