Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django pixel tracking

I'm using django to do a pixel tracker on an email

Is it easy to return an actual image from a django view (and how would this be done?) or is it easier to just return a redirect to the url where the actual image lives?

like image 693
MattoTodd Avatar asked Aug 18 '11 21:08

MattoTodd


2 Answers

You don't need an actual image for a tracker pixel. In fact, it's better if you don't have one.

Just use the view as the source for the image tag, and have it return a blank response.

like image 131
Daniel Roseman Avatar answered Sep 29 '22 14:09

Daniel Roseman


Since this was the first result on my google search and the best answer is buried in the link by Daniel (but not mentioned as the best), I figured I would just post the answer so nobody is tempted to return a blank response which as a Michael points out is not ideal.

The solution is to use a standard view and return an HttpResponse with the raw data that makes up a single pixel gif. Not having to hit the disk or redirect is a huge advantage.

Note that the url pattern 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 the view. Note that it uses cache_control to prevent requests from running wild. Firefox (along with many email clients) for instance will request the image twice every time for some reason you probably don't care about but need to worry about. By adding max_age=60 you will just get 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')
like image 38
dotcomly Avatar answered Sep 29 '22 16:09

dotcomly