Advertisement
Tyler_Elric

Untitled

Nov 12th, 2012
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.73 KB | None | 0 0
  1. # ===========================================================#
  2. # Project Management System. #
  3. # Written by Tyler Beaver, 2012. #
  4. # Feel free to use, but don't remove my name please? :) #
  5. # ===========================================================#
  6.  
  7. import os,json
  8. from time import time # For unix time-stamp. Potential problem for threading?
  9.  
  10. class Cache:
  11. objects = {}#Share objects!
  12. def __init__(self,load): self.load = load
  13. @staticmethod
  14. def needsUpdate(fn):
  15. if fn not in Cache.objects:
  16. return True
  17. if os.path.getmtime(fn) > Cache.objects[fn][1]:
  18. return True
  19. return False
  20. def load(self,fn):
  21. if Cache.needsUpdate(fn):
  22. o,m = self.load(fn),os.path.getmtime(fn)
  23. Cache.objects[fn] = (o,m)
  24. return o
  25. return Cache.objects[fn]
  26.  
  27. class DataStore:
  28.  
  29. def __init__(self,entity,*foreign,loadObject=None,saveObject=None):
  30. self.entity = entity
  31. self.foreignKeys,self.foreignLists = {},{}
  32. typeMap = {'list':self.foreignLists,'key':self.foreignKeys}
  33. for ref in foreign:
  34. a=typeMap.get(ref[0],None)
  35. if a is None:
  36. raise AssertionError("What kind of foreign object is this?")
  37. a[ref[1]] = ref[2]
  38. self.cache = Cache(self.loadObject)
  39. if not os.path.exists(self.directory):
  40. os.mkdir(self.directory)
  41.  
  42. @staticmethod
  43. def baseDirectory():return os.environ.get("FMDataStore",os.getcwd())
  44.  
  45. @property
  46. def directory(self):
  47. d = str(self.entity.__name__)
  48. return os.path.join(DataStore.baseDirectory(),d)
  49.  
  50. def create(self,**opts):return self.entity(self,**opts)
  51.  
  52. def store(self,entity):
  53. assert isinstance(entity,self.entity)
  54. fn = os.path.join(self.directory,entity.key+".json")
  55. self.saveObject(entity.dat,fn)
  56.  
  57. def loadObject(self,fn):
  58. return self.entity(self,key=fn[:fn.rfind(".")],**json.load(open(fn)))
  59.  
  60. def load(self,key,foreign=None):
  61. if foreign:
  62. print(foreign,key)
  63. return self.foreignKeys[foreign].load(key)
  64. data = self.cache.load(os.path.join(self.directory,key))
  65. return self.entity(self,key=key,**data)
  66.  
  67. def __iter__(self):
  68. def fetchAll():
  69. for fn in os.listdir(self.directory):
  70. yield self.cache.load(os.path.join(self.directory,fn))
  71. return fetchAll()
  72.  
  73. class Entity:
  74.  
  75. def __init__(self,key=int(time()),**data):
  76. self.modified = False
  77. self.key = str(key)
  78. self.dat = self.template
  79. for key in data.keys():
  80. self.dat[key] = data[key]
  81.  
  82. def __getattr__(self,attr):
  83. if attr in self.dat:
  84. v=self.dat[attr]
  85. if attr in self.storage.foreignKeys:
  86. if attr is not None:
  87. return self.storage.load(v,foreign=attr)
  88. return v
  89. t="{} entity has no attribute '{}'"
  90. raise AttributeError(t.format(type(self).__name__, attr))
  91.  
  92. def update(self,**kwargs):
  93. for key in kwargs.keys():
  94. self.modified = True
  95. self.dat[key] = kwargs[key]
  96.  
  97. class Query:
  98.  
  99. def __init__(self,db,*filters):
  100. self.source=db
  101. self.filters = list(filters)
  102.  
  103. def __iter__(self):
  104. def filter():
  105. for entity in self.source:
  106. if all(filter(entity) for filter in self.filters):
  107. yield entity
  108. return filter()
  109.  
  110. if __name__ == "__main__":
  111. class Person(Entity):
  112. def template(self):
  113. return {
  114. 'name':"",
  115. 'age':0,
  116. 'location':None
  117. }
  118.  
  119. people = DataStore(Person)
  120.  
  121. if "yes" in input("Create a new person? >"):
  122. name = input("Name> ")
  123. age = input("Age> ")
  124. location = input("Location [ or 'no']> ")
  125. location = location if location.lower()!='no' else None
  126. people.create(name=name,age=age,location=location).save()
  127.  
  128. for person in people:
  129. print(person)
  130. name = person.name
  131. age = person.age
  132. location = person.location
  133. intro = "This is {}.".format(name)
  134. b = "He is {}.".format(age) if age else "We don't know how old he is."
  135. c = "He lives in {}.".format(location) if location else "He would rather you didn't know where he lives."
  136. print(intro,b,c)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement