Part of Slepp's ProjectsPastebinTURLImagebinFilebin
Feedback -- English French German Japanese
Create Upload Newest Tools Donate
Sign In | Create Account

Advertising

dbobjects.py
Wednesday, January 30th, 2008 at 7:11:32am MST 

  1. import logging
  2. import sys
  3. import gc
  4. import os
  5.  
  6. logging.basicConfig()
  7. log = logging.getLogger("dbobjects")
  8. log.setLevel(logging.INFO)
  9.  
  10. if (sys.version_info[0] == 2 and sys.version_info[1] < 4) or sys.version_info[0] < 2:
  11.     log.exception("Unable to load library.  This library requires Python 2.4 or newer")
  12.     raise Exception("Incorrect python version - use python 2.4 or higher")
  13.  
  14. from sqlobject import *
  15. from sqlobject.sqlbuilder import *
  16.  
  17. # CREATE TABLE imports ( id INTEGER PRIM ARY KEY NOT NULL, time INTEGER
  18. # );
  19.  
  20. # CREATE TABLE meta ( id INTEGER PRIMARY KEY NOT NULL, name TEXT UNIQUE
  21. #                                 NOT NULL, data TEXT );
  22.  
  23. # CREATE TABLE photo_tags ( photo_id INTEGER, tag_id INTE GER );
  24.  
  25. # CREATE TABLE photo_versions ( photo_id INTEGER, version _id INTEGER,
  26. # name STRING );
  27.  
  28. # CREATE TABLE photos ( id INTEGER PRIMARY KEY NOT NULL, time INTEGER
  29. # NOT NULL, directory_path STRING NOT NULL, name STRING NOT NULL,
  30. # description TEXT NOT NU LL, default_version_id INTEGER NOT NULL );
  31.  
  32. # CREATE TABLE tags ( id INTEGER PR IMARY KEY NOT NULL, name TEXT
  33. # UNIQUE, cate gory_id INTEGER, is_category BOOLEAN, sort_priority
  34. # INTEGER, icon TEXT );
  35.  
  36. class PhotoVersion:
  37.     def __init__(self, id, name, photo):
  38.         self.id = id
  39.         self.name = name
  40.         self.photo = photo
  41.         self.isDefault = id == photo.defaultVersionId
  42.    
  43.     def getFilename(self):
  44.         return self.photo.directoryPath + os.sep + os.path.splitext(self.photo.name)[0] + " (" + self.name + ")"  + os.path.splitext(self.photo.name)[1]
  45.    
  46. class Photo(SQLObject):
  47.     class sqlmeta:
  48.         table = "photos"
  49.     time = IntCol()
  50.     directoryPath = UnicodeCol(notNone=True)
  51.     name = UnicodeCol(notNone=True)
  52.     description = StringCol(notNone=True)
  53.     defaultVersionId = IntCol(notNone=True)
  54.     tags = RelatedJoin('Tag', intermediateTable='photo_tags',
  55.                               joinColumn='photo_id', otherColumn='tag_id')
  56.     versions = None
  57.  
  58.     def getFilename(self, forceOriginal=False, version=None, cache=None):
  59.         if version:
  60.             try: return self.getVersions(cache)[int(version)].getFilename()
  61.             except: pass
  62.         if self.defaultVersionId > 1 and not forceOriginal:
  63.             return self.getVersions(cache)[self.defaultVersionId].getFilename()
  64.         else:
  65.             return self.directoryPath + os.sep + self.name
  66.    
  67.     # we can't have a photo_versions object because the column has no id
  68.     def getVersions(self, cache=None):
  69.         """
  70.         Performs an SQL query to get all of the versions of this file.  After this
  71.         has been called once, it will store the data for future instances.
  72.        
  73.         @param cache:  an SQLCache object if desired. This allows saving some of the
  74.         results in RAM for future use.
  75.         """
  76.         if self.versions: return self.versions
  77.         self.versions = {}
  78.         query = """SELECT version_id, name FROM photo_versions WHERE photo_id=%d""" % (self.id)
  79.         if not cache:
  80.             res = self._connection.queryAll(query)
  81.         else:
  82.             res = cache.execute(query)
  83.         for r in res:
  84.             self.versions[r[0]] = PhotoVersion(r[0], r[1], self)
  85.         return self.versions
  86.            
  87.  
  88. class TagRepr:
  89.     """Representation of a tag that is not dependent on SQLObject.
  90.    
  91.     This class is used when we do things with tags that don't require the
  92.     SQLObject interface but still need an object oriented interface
  93.     """
  94.     def __init__(self, id=None, name=None, categoryId=None, numPhotos=None):
  95.         self.id = id
  96.         self.name = name
  97.         self.categoryId = categoryId
  98.         self.numPhotos=numPhotos
  99.        
  100. class Tag(SQLObject):
  101.     class sqlmeta:
  102.         table = "tags"
  103.     name = UnicodeCol(notNone=True, alternateID=True)
  104.     categoryId = IntCol()
  105.     isCategory = BoolCol()
  106.     sortPriority = IntCol()
  107.     icon = StringCol()
  108.     children = MultipleJoin('Tag', joinColumn='category_id')
  109.     def toTagRepr(self):
  110.         return TagRep(it=self.id, name=self.name, categoryId=self.categoryId)
  111.    
  112. def expire_all():
  113.     """Simple function to expire the cache from everything.  Call
  114.     it periodically to keep stuff happy
  115.  
  116.     taken from: http://mikewatkins.net/categories/technical/2004-07-14-1.html
  117.     """
  118.     c = Study._connection
  119.     for k in c.cache.caches.keys():
  120.         c.cache.caches[k].expireAll()
  121.     gc.collect()
  122.  
  123. def setConnection(conn):
  124.     for x in [y for y in globals().values() if hasattr(y,'setConnection')
  125.               and y.__class__.__name__ == 'DeclarativeMeta'
  126.               and not y.__module__.startswith('sqlobject')]:
  127.         x.setConnection(conn)
  128.         print "setting connection on ", x
  129.  
  130. def connect(uri, debug=False, cache=None, process=True):
  131.     global connection
  132.     global sqlhub
  133.    
  134.     connection = connectionForURI(uri)
  135.     if process:
  136.         sqlhub.processConnection = connection
  137.  
  138.     if debug:
  139.         connection.debug = True
  140.     if cache != None:
  141.         connection.cache = cache
  142.     return connection

Paste Details

advertising

Update the Post

Either update this post and resubmit it with changes, or make a new post.

You may also comment on this post.

update paste below
details of the post (optional)

Note: Only the paste content is required, though the following information can be useful to others.

Save name / title?

(space separated, optional)



Please note that information posted here will expire by default in one month. If you do not want it to expire, please set the expiry time above. If it is set to expire, web search engines will not be allowed to index it prior to it expiring. Items that are not marked to expire will be indexable by search engines. Be careful with your passwords. All illegal activities will be reported and any information will be handed over to the authorities, so be good.

fantasy-obligation