Permalink
Browse files

Moving a bunch of stuff around...

  • Loading branch information...
1 parent 116a404 commit ac57db0357c95a1d9ac306904f89543dec497539 @johnboxall johnboxall committed Feb 18, 2009
Showing with 156 additions and 135 deletions.
  1. +2 −0 README.md
  2. +1 −0 __init__.py
  3. +100 −70 helpers.py → admob.py
  4. +3 −18 decorators.py
  5. +6 −3 middleware.py
  6. +44 −44 templatetags/admob_tags.py
View
@@ -52,3 +52,5 @@ Technicals:
`admob.middleware.AdMobMiddleware` is needed because AdMob uses cookies to help track users. The middleware steps in at the `process_response` phase and looks if any AdMob actions happened by checking if `request.has_admob = True`. If so it sets an AdMob cookie on the response.
Secondly there is some stuff going on with `request.admobuu` - this is the value that the AdMob cookie will eventually have. It's also needed for the AdMob interactions - so we might end up calculating it early and storing it in `request.admobuu` for later use in the middleware.
+
+If you are caching responses with AdMob ads be sure to remove the 'admobuu' attribute from requests so it will be recalculated?
View
@@ -0,0 +1 @@
+from admob import *
View
@@ -3,6 +3,7 @@
import random
import urllib
import urllib2
+from string import split as L
from django.conf import settings
from django.utils.http import cookie_date
@@ -14,13 +15,14 @@
ANALYTICS_ID = getattr(settings, 'ADMOB_ANALYTICS_ID')
COOKIE_PATH = getattr(settings, 'ADMOB_COOKIE_PATH', '/')
COOKIE_DOMAIN = getattr(settings, 'ADMOB_COOKIE_DOMAIN', settings.SESSION_COOKIE_DOMAIN)
-ENCODING = getattr(settings, 'ADMOB_ENCODING', 'utf-8')
+ENCODING = getattr(settings, 'ADMOB_ENCODING', settings.DEFAULT_CHARSET)
TEST = getattr(settings, 'ADMOB_TEST', True)
ENDPOINT = "http://r.admob.com/ad_source.php"
TIMEOUT = 1 # Timeout in seconds.
-PUBCODE_VERSION = "20090116-DJANGO"
-IGNORE = "HTTP_PRAGMA HTTP_CACHE_CONTROL HTTP_CONNECTION HTTP_USER_AGENT HTTP_COOKIE".split()
+PUBCODE_VERSION = "20090217-DJANGO"
+IGNORE = L("HTTP_PRAGMA HTTP_CACHE_CONTROL HTTP_CONNECTION HTTP_USER_AGENT HTTP_COOKIE")
+
class AdMobError(Exception):
"Base class for AdMob exceptions."
@@ -32,15 +34,24 @@ class AdMob(object):
"""
def __init__(self, request, params=None, fail_silently=False):
"""
- `request` - a Django HttpRequest object
- `params` - a dict of parameters to pass to AdMob
- `fail_silently` - set to True to catch exceptions.
+ * request - HttpRequest object
+ * params - dict of parameters to pass to AdMob
+ * fail_silently - set to True to raise HTTP exceptions
"""
self.request = request
- self.session_id = getattr(request.session, 'session_key', None)
self.params = params or {}
self.fail_silently = fail_silently
+ self.session_id = getattr(request.session, 'session_key', None)
+
+ def fetch(self):
+ """
+ Make an AdMob request!
+
+ """
+ self.build_post_data()
+ return self._fetch()
+
def build_post_data(self):
"""
@@ -66,57 +77,71 @@ def build_post_data(self):
# AdMob cookie - If it hasn't been set yet then set it.
if 'admobuu' not in self.request.COOKIES:
if not hasattr(self.request, 'admobuu'):
- self.admobuu = _admob_cookie_value(self.request)
+ self.admobuu = cookie_value(self.request)
self.request.admobuu = self.admobuu
else:
self.admobuu = self.request.admobuu
else:
self.admobuu = self.request.COOKIES['admobuu']
-
+
+ # Shared parameters.
self.post_data = {
- 'rt': self.request_type,
- 'z': time.time(),
- 'u': self.request.META.get('HTTP_USER_AGENT'),
- 'i': self.request.META.get('REMOTE_ADDR'),
- 'p': self.request.build_absolute_uri(),
- 't': self.admob_session_id,
- 'v': PUBCODE_VERSION,
- 'o': self.admobuu,
- 's': self.params.get('publisher_id', PUBLISHER_ID),
- 'a': self.params.get('analytics_id', ANALYTICS_ID),
- 'ma': self.params.get('markup'),
- 'd[pc]': self.params.get('postal_code'),
- 'd[ac]': self.params.get('area_code'),
- 'd[coord]': self.params.get('coordinates'),
- 'd[dob]': self.params.get('dob'),
- 'd[gender]': self.params.get('gender'),
- 'k': self.params.get('keywords'),
- 'search': self.params.get('search'),
- 'f': self.params.get('format', 'html'),
- 'title': self.params.get('title'),
- 'event': self.params.get('event'),
- 'p': self.params.get('page', self.request.build_absolute_uri())
+ 'rt': self.request_type, # admob request type
+ 'u': self.request.META.get('HTTP_USER_AGENT'), # user agent
+ 'i': self.request.META.get('REMOTE_ADDR'), # ip address
+ 't': self.admob_session_id, # AdMob session id
+ 'o': self.admobuu, # AdMob cookie value
+ 'p': self.params.get('page', self.request.build_absolute_uri()), # page for your reference
+ 'v': PUBCODE_VERSION, # code version
+ 'z': round(time.time(), 2), # current timestamp
}
- # Add in header data.
+ # Header.
for header, value in self.request.META.iteritems():
if header.startswith("HTTP") and header not in IGNORE:
self.post_data["h[%s]" % header] = value
- # Add in optional data.
+ # Test.
self.test = self.params.get('test', TEST)
if self.test:
self.post_data['m'] = 'test'
- self.encoding = self.params.get('encoding', ENCODING)
- if self.encoding:
- self.post_data['e'] = self.encoding
- if 'text_only' in self.params:
- self.post_data['y'] = 'text'
-
+
+ # Analytics specific parameters.
+ if self.analytics_request:
+ self.post_data.update({
+ 'a': self.params.get('analytics_id', ANALYTICS_ID),
+ 'title': self.params.get('title'), # page title for your reference
+ 'event': self.params.get('event') # event for your reference
+ })
+
+ # Ad specific parameters.
+ if self.ad_request:
+ self.post_data.update({
+ 's': self.params.get('publisher_id', PUBLISHER_ID), # admob publisher id
+ 'ma': self.params.get('markup'), # xhtml / wml
+ 'f': self.params.get('format'), # html / html_no_js
+ 'd[pc]': self.params.get('postal_code'),
+ 'd[ac]': self.params.get('area_code'),
+ 'd[coord]': self.params.get('coordinates'), # lat,lng
+ 'd[dob]': self.params.get('dob'), # date of birth
+ 'd[gender]': self.params.get('gender'),
+ 'k': self.params.get('keywords'), # space seperated keywords
+ 'search': self.params.get('search') # visitor search term
+ })
+
+ # Text only.
+ if 'text_only' in self.params:
+ self.post_data['y'] = 'text'
+
+ # Output encoding.
+ self.encoding = self.params.get('encoding', ENCODING)
+ if self.encoding:
+ self.post_data['e'] = self.encoding
+
# Don't send anything that is None.
- self.post_data = dict((k, v) for k, v in self.post_data.iteritems() if v is not None)
+ self.post_data = dict((k, v) for k, v in self.post_data.iteritems() if v is not None)
- def fetch(self):
+ def _fetch(self):
"""
Fetch the AdMob resource using urllib2.urlopen.
@@ -125,7 +150,10 @@ def fetch(self):
original_timeout = socket.getdefaulttimeout()
socket.setdefaulttimeout(TIMEOUT)
try:
- self.response = urllib2.urlopen(ENDPOINT, urllib.urlencode(self.post_data))
+ self.response = urllib2.urlopen(ENDPOINT, urllib.urlencode(self.post_data))
+ print 'sending data...'
+ import pprint
+ pprint.pprint(self.post_data)
except urllib2.URLError, e:
if self.fail_silently:
return ''
@@ -137,50 +165,52 @@ def fetch(self):
socket.setdefaulttimeout(original_timeout)
-def set_admob_cookie(request, response, params=None):
+def cookie_value(request):
+ """
+ Construct an AdMob cookie value from user-agent and ip.
+
+ """
+ s = "%f%s%s%f" % (
+ random.random(),
+ request.META.get('HTTP_USER_AGENT', ''),
+ request.META.get('REMOTE_ADDR', ''),
+ time.time()
+ )
+ print "COOKIE_VALUE: %s" % s
+ return md5_constructor(s).hexdigest()
+
+def set_cookie(request, response, params=None):
"""
- Given a `response` and `request` set an AdMob cookie.
+ Given request set and AdMob cookie on response.
"""
params = params or {}
+
# Don't make a new cookie if one already exists
if 'admobuu' in request.COOKIES:
return response
+
# Make a new cookie
if hasattr(request, 'admobuu'):
value = request.admobuu
- else:
- value = _admob_cookie_value(request)
+ else:
+ value = cookie_value(request)
+
+ # Set the cookie on the response.
expires = cookie_date(0x7fffffff) # End of 32 bit time.
path = params.get('cookie_path', COOKIE_PATH)
domain = params.get('cookie_domain', COOKIE_DOMAIN)
response.set_cookie('admobuu', value, expires=expires, path=path, domain=domain)
return response
-
-def _admob_cookie_value(request):
- "Return the AdMob cookie value for this `request`."
- s = "%f%s%s%f" % (
- random.random(),
- request.META.get('HTTP_USER_AGENT', ''),
- request.META.get('REMOTE_ADDR', ''),
- time.time()
- )
- return md5_constructor(s).hexdigest()
+
+def analytics(request, params=None, fail_silently=False):
+ params = params or {}
+ params.update({"analytics_request": True, "ad_request": False})
+ admob = AdMob(request, params, fail_silently)
+ return admob.fetch()
-def admob(request, params=None, fail_silently=False):
- "Ad and Analytics."
- return _admob(request, dict(analytics_request=True, ad_request=True), fail_silently)
-
-def admob_ad(request, params=None, fail_silently=False):
- "Ad only."
- return _admob(request, dict(analytics_request=False, ad_request=True), fail_silently)
-
-def admob_analytics(request, params=None, fail_silently=False):
- "Analytics only."
- return _admob(request, dict(analytics_request=True, ad_request=False), fail_silently)
-
-def _admob(request, params=None, fail_silently=False):
+def ad(request, params=None, fail_silently=False):
params = params or {}
+ params.update({"analytics_request": False, "ad_request": True})
admob = AdMob(request, params, fail_silently)
- admob.build_post_data()
return admob.fetch()
View
@@ -3,32 +3,17 @@
except ImportError:
from django.utils.functional import update_wrapper # Python 2.3, 2.4 fallback.
-from admob.helpers import set_admob_cookie, admob_analytics
+from admob import analytics
def analytics(view):
"""
Construct an AdMob analytics request.
- Use with `admob.middleware.AdMobMiddleware`.
+ Requires admob.middleware.AdMobMiddleware.
"""
def _dec(request, *args, **kwargs):
- admob_analytics(request, params=None, fail_silently=False)
+ analytics(request, params=None, fail_silently=False)
request.has_admob = True
return view(request, *args, **kwargs)
- return _dec
-
-
-def analytics_and_cookie(view):
- """
- Construct an AdMob analytics for `request` and then an AdMob cookie
- on the `response`. Be aware that this evaluates `view` and returns a
- response object (won't play nice with other decorators!)
-
- """
- def _dec(request, *args, **kwargs):
- admob_analytics(request, params=None, fail_silently=False)
- response = view(request, *args, **kwargs)
- response = set_admob_cookie(request , response)
- return response
return _dec
View
@@ -1,9 +1,12 @@
-from admob.helpers import set_admob_cookie
+from admob import set_cookie
class AdMobMiddleware(object):
def process_response(self, request, response):
- "If an AdMob function has been called then set an AdMob cookie on the response."
+ """
+ Sets an AdMob cookie if required.
+
+ """
if getattr(request, 'has_admob', False):
- response = set_admob_cookie(request, response)
+ response = set_cookie(request, response)
return response
Oops, something went wrong.

0 comments on commit ac57db0

Please sign in to comment.