Package turbogears :: Package visit :: Module sovisit

Source Code for Module turbogears.visit.sovisit

  1  from datetime import datetime 
  2   
  3  from sqlobject import SQLObject, SQLObjectNotFound, StringCol, DateTimeCol 
  4  from sqlobject.sqlbuilder import Update 
  5   
  6  from turbogears import config 
  7  from turbogears.database import PackageHub 
  8  from turbogears.util import load_class 
  9  from turbogears.visit.api import BaseVisitManager, Visit 
 10   
 11  hub = PackageHub('turbogears.visit') 
 12  __connection__ = hub 
 13   
 14  import logging 
 15   
 16  log = logging.getLogger('turbogears.visit.sovisit') 
 17   
 18  visit_class = None 
19 20 21 -class SqlObjectVisitManager(BaseVisitManager):
22
23 - def __init__(self, timeout):
24 global visit_class 25 visit_class_path = config.get('visit.soprovider.model', 26 'turbogears.visit.sovisit.TG_Visit') 27 visit_class = load_class(visit_class_path) 28 if visit_class: 29 log.info("Successfully loaded '%s'", visit_class_path) 30 # base-class' __init__ triggers self.create_model, so mappers need to 31 # be initialized before. 32 super(SqlObjectVisitManager, self).__init__(timeout)
33
34 - def create_model(self):
35 hub.begin() 36 visit_class.createTable(ifNotExists=True) 37 hub.commit() 38 hub.end() 39 log.debug("Visit model database table(s) created.")
40
41 - def new_visit_with_key(self, visit_key):
42 hub.begin() 43 visit = visit_class(visit_key=visit_key, 44 expiry = datetime.now() + self.timeout) 45 hub.commit() 46 hub.end() 47 return Visit(visit_key, True)
48
49 - def visit_for_key(self, visit_key):
50 """Return the visit for this key. 51 52 Returns None if the visit doesn't exist or has expired. 53 54 """ 55 try: 56 expiry = self.queue[visit_key] 57 except KeyError: 58 visit = visit_class.lookup_visit(visit_key) 59 if not visit: 60 return None 61 expiry = visit.expiry 62 now = datetime.now() 63 if expiry < now: 64 return None 65 # Visit hasn't expired, extend it 66 self.update_visit(visit_key, now + self.timeout) 67 return Visit(visit_key, False)
68
69 - def update_queued_visits(self, queue):
70 if hub is None: 71 return # if VisitManager extension wasn't shutted down cleanly 72 hub.begin() 73 try: 74 conn = hub.getConnection() 75 try: 76 # Now update each of the visits with the most recent expiry 77 for visit_key, expiry in queue.items(): 78 u = Update(visit_class.q, 79 {visit_class.q.expiry.fieldName: expiry}, 80 where=(visit_class.q.visit_key == visit_key)) 81 conn.query(conn.sqlrepr(u)) 82 hub.commit() 83 except: 84 hub.rollback() 85 raise 86 finally: 87 hub.end()
88
89 90 -class TG_Visit(SQLObject):
91
92 - class sqlmeta:
93 table = 'visit'
94 95 visit_key = StringCol(length=40, alternateID=True, 96 alternateMethodName='by_visit_key') 97 created = DateTimeCol(default=datetime.now) 98 expiry = DateTimeCol() 99 100 @classmethod
101 - def lookup_visit(cls, visit_key):
102 try: 103 return cls.by_visit_key(visit_key) 104 except SQLObjectNotFound: 105 return None
106