Commits

ken cochrane committed 1df9d46 Merge

merging in pull request from pydanny

Comments (0)

Files changed (14)

 Add the visitor middleware::
 
     MIDDLEWARE_CLASSES = (
-        'visitor.middleware.visitor_middleware.VisitorMiddleware'
+        ...
+        'visitor.middleware.VisitorMiddleware'
         ...
     )
 
 
     python manage.py syncdb
 
-Custom Settings
----------------
+Required Settings
+-----------------
 
 Add the following two properties to your settings file::
 
         Default = 31536000 # or 1 year.
         # This is how long the cookie will live in your visitors browser before it expires on it's own
         COOKIE_MAX_AGE = 31536000 # 1 year
+
+Custom settings
+---------------
+
+These settings can be overridden::
+
+    VISITOR_KEY
+        Default = 'visitor_key'
+
+    COOKIE_SAVED
+        Default = 'cookie_saved'
+
+    COOKIE_VISITOR_KEY
+        Default = 'vk'
+
+    REQUEST_LOG_ID
+        Default = 'request_log_id'
         
 References
 ----------
 .. toctree::
     :maxdepth: 2
 
+    ref_visitor_managers
+    ref_visitor_middleware
+    ref_visitor_models
     ref_visitor_utils
+    
 
 
 Indices and tables

docs/ref_visitor_managers.rst

+============================
+Visitor Managers Reference
+============================
+
+
+.. automodule:: visitor.managers
+  :members:
+  :undoc-members:

docs/ref_visitor_middleware.rst

+============================
+Visitor Middleware Reference
+============================
+
+
+.. automodule:: visitor.middleware
+  :members:
+  :undoc-members:

docs/ref_visitor_models.rst

+============================
+Visitor Models Reference
+============================
+
+
+.. automodule:: visitor.models
+  :members:
+  :undoc-members:

visitor/cache_utils.py

+from django.core.cache import cache
+
+CACHE_TIMEOUT = 60 * 60 * 1 # one hour
+
+def make_cache_key(visitor_key):
+    """ make the cache key for visitor """
+    return 'visitor_%s' % (visitor_key)
+
+def check_cache(visitor_key):
+    """ check the cache for this visitor """
+    cached = cache.get(make_cache_key(visitor_key))
+    if cached:
+       return cached
+       
+    return None
+
+def set_cache(visitor):
+    """ set the visitor object in the cache """
+    if visitor.visitor_key:
+        cache_key = make_cache_key(visitor.visitor_key) 
+        cache.set(cache_key, visitor, CACHE_TIMEOUT)

visitor/managers.py

 from django.db import models
 
-#===============================================================================
 class VisitorManager(models.Manager):
     
-    #---------------------------------------------------------------------------
     def find_visitor(self, visitor_key):
         try:
             return self.get(visitor_key=visitor_key)
         except self.model.DoesNotExist:
-            print("model doesn't exist")
-            return None
-            
-    #---------------------------------------------------------------------------
-    def create_from_ip(self, ip):
-        from visitor.visitor_utils import create_uuid
-        return self.get_or_create(visitor_key=create_uuid(ip))[0]
-        
+            return None

visitor/middleware.py

+"""
+Visitor's Middleware, it will look to see if we already registered this visitor
+if not, it will create a cookie, and create a visitor record for future tracking. 
+If we already know about them we get their visitor record and update it.
+"""
+from django import http
+
+import visitor.visitor_utils as utils
+from visitor import visitor_constants as constants
+
+
+class VisitorMiddleware(object):
+    """ 
+    Visitors middleware it will look to see if we already registered this 
+    visitor if not, it will create a cookie, and create a visitor record for 
+    future tracking. If we already know about them we get their visitor record 
+    and update it.
+    """
+
+    def process_request(self, request):
+        """ get or set the visitor cookie """
+        # figure out the IP
+        ip_address = utils.ip_address_from_request(request) or 'Unknown'
+
+        # we check to see if they have a cookie, if they do we update the stats
+        # for the cookie if they don't have a cookie, we create the cookie.
+        # then we associate that cookie to the web request 
+        # later on in the response if we haven't set the cookie yet, we will 
+        # set the cookie in the browser.
+        
+        cookie_saved = request.session.get(constants.COOKIE_SAVED, None)
+        visitor_key = request.session.get(constants.VISITOR_KEY, None)
+        visitor_key_cookie = utils.get_visitor_cookie_key(request)
+        
+        # print("cookie saved = %s" % cookie_saved)
+        # print("visitor_key = %s" % visitor_key)
+        # print("visitor_key_cookie = %s" % visitor_key_cookie)
+        
+        # if we have a visitor key, and cookie_saved from session
+        # and we get a cookie and the cookie's visitor key matches the one 
+        # in the session then we don't need to continue, everything is all
+        # set.
+        #
+        # if we wanted to update the visitor every time they made a request
+        # we wouldn't do this, but that would take a lot of resources for
+        # large sites, so we will defer that to a future version for now.
+        if (visitor_key and 
+            cookie_saved and 
+            visitor_key_cookie and 
+            visitor_key == visitor_key_cookie):
+                return None
+        
+        session_key = request.session.session_key
+        # print("session_key = %s" % session_key)
+        
+        if visitor_key_cookie:
+            request.session[constants.COOKIE_SAVED] = True
+            visitor = utils.update_visitor(visitor_key_cookie, 
+                                     session_key=session_key)
+                                     
+            if not visitor:
+                # we couldn't find their old cookie, so create a new one.
+                request.session[constants.COOKIE_SAVED] = False
+                visitor = utils.create_visitor(ip_address, session_key)
+                                         
+        else:
+            request.session[constants.COOKIE_SAVED] = False
+            visitor = utils.create_visitor(ip_address, session_key)
+
+        request.session[constants.VISITOR_KEY] = visitor.visitor_key
+        return None
+
+    def process_response(self,request, response):
+        """ look if we need to save the visitor cookie """
+        if hasattr(request, 'session'):
+            cookie_saved = request.session.get(constants.COOKIE_SAVED, None)
+            visitor_key = request.session.get(constants.VISITOR_KEY, None)
+            if not cookie_saved and visitor_key:
+                utils.set_visitor_cookie_from_key(response, visitor_key)
+                request.session[constants.COOKIE_SAVED] = True
+        return response

visitor/middleware/__init__.py

Empty file removed.

visitor/middleware/visitor_middleware.py

-"""
-Visitor's Middleware, it will look to see if we already registered this visitor
-if not, it will create a cookie, and create a visitor record for future tracking. 
-If we already know about them we get their visitor record and update it.
-"""
-from django import http
-
-from visitor.visitor_utils import *
-from visitor import visitor_constants as constants
-
-
-#===============================================================================
-class VisitorMiddleware(object):
-    """ 
-    Visitors middleware it will look to see if we already registered this 
-    visitor if not, it will create a cookie, and create a visitor record for 
-    future tracking. If we already know about them we get their visitor record 
-    and update it.
-    """
-
-    #--------------------------------------------------------------------------
-    def process_request(self, request):
-        """ get or set the visitor cookie """
-        # figure out the IP
-        ip_address = ip_address_from_request(request) or 'Unknown'
-
-        # we check to see if they have a cookie, if they do we update the stats
-        # for the cookie if they don't have a cookie, we create the cookie.
-        # then we associate that cookie to the web request 
-        # later on in the response if we haven't set the cookie yet, we will 
-        # set the cookie in the browser.
-        
-        cookie_saved = request.session.get(constants.COOKIE_SAVED, None)
-        visitor_key = request.session.get(constants.VISITOR_KEY, None)
-        visitor_key_cookie = get_visitor_cookie_key(request)
-        
-        # print("cookie saved = %s" % cookie_saved)
-        # print("visitor_key = %s" % visitor_key)
-        # print("visitor_key_cookie = %s" % visitor_key_cookie)
-        
-        # if we have a visitor key, and cookie_saved from session
-        # and we get a cookie and the cookie's visitor key matches the one 
-        # in the session then we don't need to continue, everything is all
-        # set.
-        #
-        # if we wanted to update the visitor every time they made a request
-        # we wouldn't do this, but that would take a lot of resources for
-        # large sites, so we will defer that to a future version for now.
-        if (visitor_key and 
-            cookie_saved and 
-            visitor_key_cookie and 
-            visitor_key == visitor_key_cookie):
-                return None
-        
-        session_key = request.session.session_key
-        # print("session_key = %s" % session_key)
-        
-        if visitor_key_cookie:
-            request.session[constants.COOKIE_SAVED] = True
-            visitor = update_visitor(visitor_key_cookie, 
-                                     session_key=session_key)
-                                     
-            if not visitor:
-                # we couldn't find their old cookie, so create a new one.
-                request.session[constants.COOKIE_SAVED] = False
-                visitor = create_visitor(ip_address, session_key)
-                                         
-        else:
-            request.session[constants.COOKIE_SAVED] = False
-            visitor = create_visitor(ip_address, session_key)
-
-        request.session[constants.VISITOR_KEY] = visitor.visitor_key
-        return None
-
-    #--------------------------------------------------------------------------
-    def process_response(self,request, response):
-        """ look if we need to save the visitor cookie """
-        if hasattr(request, 'session'):
-            cookie_saved = request.session.get(constants.COOKIE_SAVED, None)
-            visitor_key = request.session.get(constants.VISITOR_KEY, None)
-            if not cookie_saved and visitor_key:
-                set_visitor_cookie_from_key(response, visitor_key)
-                request.session[constants.COOKIE_SAVED] = True
-        return response

visitor/models.py

 
 from datetime import datetime
 
-#==============================================================================
 class Visitor(models.Model):
     visitor_key = models.CharField(max_length='50', db_index=True)
     created = models.DateTimeField(default=datetime.now())
     
     objects = managers.VisitorManager()
     
-    #---------------------------------------------------------------------------
     def __unicode__(self):
         return '#%d/%s' % (self.id, self.last_session_key)
         
-    #--------------------------------------------------------------------------
     def generate_key(self, ip_address):
         if not self.visitor_key:
             from visitor.visitor_utils import create_uuid
             self.visitor_key = create_uuid(ip_address)
         return self.visitor_key
 
-    #--------------------------------------------------------------------------
     def mark_visit(self):
         self.num_visits += 1
 
-    #--------------------------------------------------------------------------
     def save(self, *args, **kws):
         self.last_update = datetime.now()
         super(Visitor, self).save(*args, **kws)
         
-    #--------------------------------------------------------------------------
     @property
     def session(self):
         try:
         except Session.DoesNotExist:
             return None
             
-    #--------------------------------------------------------------------------
     @property      
     def user():
         """ 

visitor/tests/__init__.py

+from visitor.tests.test_models import *

visitor/tests/test_models.py

+from datetime import datetime
+
+from django.contrib.sites.models import Site
+from django.core.cache import cache
+from django.http import HttpResponse
+from django.test import TestCase
+
+from visitor.models import Visitor
+
+class BaseTestCase(TestCase):
+        
+    def tearDown(self):
+        super(BaseTestCase,self).setUp()        
+        cache.clear()
+
+class VisitorModelTest(BaseTestCase):
+
+    def test_create_visitor(self):
+
+        count = Visitor.objects.count()
+        visitor = Visitor.objects.create(
+            visitor_key = 'abcdefg',
+            last_session_key = 'hijklmnop'
+        )
+        visitor.save()
+        self.assertTrue(count < Visitor.objects.count())
+
+    """ test on possibly deprecated method
+    def test_manager_create_from_ip(self):
+        ip = '127.0.0.1'
+        visitor = Visitor.objects.create_from_ip(ip)
+        self.assertEquals(Visitor.objects.count(), 1)
+        
+        visitor = Visitor.objects.create_from_ip(ip)
+        self.assertEquals(Visitor.objects.count(), 1)        
+    """

visitor/visitor_constants.py

-VISITOR_KEY = 'visitor_key'
-COOKIE_SAVED = 'cookie_saved'
-COOKIE_VISITOR_KEY = 'vk'
-REQUEST_LOG_ID = 'request_log_id'
+from django.conf import settings
+
+VISITOR_KEY = getattr(settings, 'VISITOR_KEY', 'visitor_key')
+COOKIE_SAVED = getattr(settings, 'COOKIE_SAVED', 'cookie_saved')
+COOKIE_VISITOR_KEY = getattr(settings, 'COOKIE_VISITOR_KEY', 'vk')
+REQUEST_LOG_ID = getattr(settings, 'REQUEST_LOG_ID', 'request_log_id')

visitor/visitor_utils.py

 
     return ip_address
 
-def get_visitor(visitor_key):
-    """ get the visitor using the visitor key """
-    return Visitor.objects.find_visitor(visitor_key)
-
 def create_visitor(ip_address,session_key):
     """ Create the visitor given an ip_address """
     visitor = Visitor()