Django pixel tracking

I am using django to create an email tracker

Is it easy to return the real image from the django view (and how to do it?) Or is it easier to just return the redirect to the URL where the real image lives?

+7
source share
3 answers

You do not need the actual image for the pixel tracker. In fact, it is better if you do not have it.

Just use the view as the source for the image tag and ask it to return an empty response.

+6
source

Since this was the first result in my Google search, and the best answer was buried in Daniel’s link (but not mentioned as the best), I decided that I would simply post the answer, so no one was tempted to return an empty answer which, as Michael points out, is not perfect .

The solution is to use the standard view and return an HttpResponse with raw data making up a single pixel gif. You cannot get to disk or redirect this huge advantage.

Please note that the url template uses the tracking code as the image name, so there is no obvious code = jf8992jf in the url.

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'), ) 

And here is a look. Note that it uses cache_control to prevent crazy requests. Firefox (along with many email clients), for example, will request an image twice each time for some reason, which probably does not bother, but need to worry about. By adding max_age = 60, you will receive only one request per minute.

 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') 
+3
source

Django has a helper static file helper that can be used to serve the image, but it is not recommended due to performance. I believe that having an idea of ​​what accounting does for pixel tracking, then redirects to the URL that serves the actual image through the web server . give you better performance.

+2
source

All Articles