django像素跟踪

Mat*_*odd 8 django tracking image

我正在使用django在电子邮件上做一个像素跟踪器

从django视图返回实际图像是否容易(以及如何完成?)或者是否更容易将重定向返回到实际图像所在的URL?

Dan*_*man 6

您不需要跟踪器像素的实际图像.事实上,如果你没有它,那就更好了.

只需使用视图作为图像标记的源,并让它返回空白响应.

  • 为了记录,我注意到发送空白响应可能会产生问题 - 至少在Chrome上的gmail中,这会导致消息中出现破损的图像字形.最好是传输一个琐碎的图像,[由Russell Keith-Magee建议](https://groups.google.com/forum/#!topic/django-users/-xiaSqXdWvc). (5认同)

dot*_*mly 5

由于这是我谷歌搜索的第一个结果,最好的答案被隐藏在Daniel的链接中(但没有被提及为最佳),我想我会发布答案,所以没有人想要回复一个空白的回复,作为一个迈克尔指出并不理想.

解决方案是使用标准视图并返回带有构成单个像素gif的原始数据的HttpResponse.不必点击磁盘或重定向是一个巨大的优势.

请注意,url模式使用跟踪代码作为图像名称,因此url中没有明显的?code = 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'),
)
Run Code Online (Sandbox Code Playgroud)

这是观点.请注意,它使用cache_control来防止请求运行wild.例如,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')
Run Code Online (Sandbox Code Playgroud)