Created
April 25, 2011 22:03
-
-
Save mtigas/941350 to your computer and use it in GitHub Desktop.
Django middleware to aid in implementing support for "Do Not Track" HTTP headers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A Django middleware, to aid in implementing the HTTP header-based | |
"Do Not Track" mechanism described in [1] and a few of the myriad variations. | |
Known browsers utilizing this option include Firefox 4+, Internet Explorer 9+, | |
and Safari under Mac OS X 10.7. | |
This does nothing by itself. It remains the application's responsibility to | |
ensure that the `tracking_opt_out` attribute is used to toggle first party | |
tracking and disable or notify third parties of the user's preference. | |
[1] http://tools.ietf.org/html/draft-mayer-do-not-track-00 | |
""" | |
__author__ = "Mike Tigas <mike@tig.as>" | |
__license__ = "Public domain; http://creativecommons.org/publicdomain/zero/1.0/" | |
class TrackingCheck(object): | |
""" | |
Sets `request.tracking_opt_out=True` if the request has one of the known | |
"do not track" explicit opt-out HTTP headers. | |
Sets a `DNT` response header back to the client, confirming that we | |
understand "do not track" headers, at the very least. | |
""" | |
def process_request(self, request): | |
# DNT: 1 | |
optout = request.META.get("HTTP_DNT", False) \ | |
or request.META.get("HTTP_X_DNT", "0") | |
if optout.strip() == "1": | |
setattr(request, "tracking_opt_out", True) | |
return None | |
# X-Do-Not-Track: 1 | |
optout = request.META.get("HTTP_X_DO_NOT_TRACK", "0") | |
if optout.strip() == "1": | |
setattr(request, "tracking_opt_out", True) | |
return None | |
# X-Tracking-Choice: do-not-track | |
optout = request.META.get("HTTP_X_TRACKING_CHOICE", False) \ | |
or request.META.get("HTTP_TRACKING_PREFERENCE", "") | |
if optout.strip() == "do-not-track": | |
setattr(request, "tracking_opt_out", True) | |
return None | |
setattr(request, "tracking_opt_out", False) | |
def process_response(self, request, response): | |
# We're actually not doing anything with `request.tracking_opt_out` | |
# at the moment. | |
response['DNT'] = "0 (sorry)" | |
# TODO | |
#response['DNT'] = "1" | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment