Mat*_*odd 8 django tracking image
我正在使用django在电子邮件上做一个像素跟踪器
从django视图返回实际图像是否容易(以及如何完成?)或者是否更容易将重定向返回到实际图像所在的URL?
您不需要跟踪器像素的实际图像.事实上,如果你没有它,那就更好了.
只需使用视图作为图像标记的源,并让它返回空白响应.
由于这是我谷歌搜索的第一个结果,最好的答案被隐藏在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)