#-*-Coding: UTF-8 -*- Import web Import config # custom configuration class, which can be ignored Def _ connect_to_db (): Return web. database (dbn = "sqlite", db = config. dbname) Def init_db (): Db = _ connect_to_db () For statement in config. SQL _statements: Db. query (statement) Class ModelError (Exception ): "Exception raised by all models. Attributes: Msg: Error message. """ Def _ init _ (self, msg = ""): Self. msg = msg Def _ str _ (self ): Return "ModelError: % s" % self. msg Class modeldefamanager Manager (object ): "ModelManager implements query functions against a model. Attributes: Cls: The class to be managed. """ Def _ init _ (self, cls ): Self. cls = cls Self. _ table_name = cls. _ name _. lower () Def all (self ): Db = _ connect_to_db () Results = db. select (self. _ table_name) Return [self. cls (x) for x in results] Def get (self, query_vars, where ): Results = self. filter (query_vars, where, limit = 1) If len (results)> 0: Return results [0] Else: Return None Def filter (self, query_vars, where, limit = None ): Db = _ connect_to_db () Try: Results = db. select (self. _ table_name, vars = query_vars, where = where, Limit = limit) Except T (Exception) as e: Raise ModelError (str (e )) Return [self. cls (x) for x in results] Class ModelMetaClass (type ): Def _ new _ (cls, classname, bases, attrs ): New_class = super (ModelMetaClass, cls). _ new _ (cls, classname, Bases, attrs) Objects = modeldefamanager Manager (new_class) Setattr (new_class, "objects", objects) Return new_class Class Model (object ): "Parent class of all models. """ _ Metaclass _ = ModelMetaClass Def _ init _ (self ): Pass Def _ table_name (self ): Return self. _ class _. _ name _. lower () Def insert (self, ** kargs ): Db = _ connect_to_db () Try: With db. transaction (): Db. insert (self. _ table_name (), ** kargs) Except T (Exception) as e: Raise ModelError (str (e )) Def delete (self, where, using = None, vars = None ): Db = _ connect_to_db () Try: With db. transaction (): Db. delete (self. _ table_name (), where, vars = vars) Except T (Exception) as e: Raise ModelError (str (e )) Def save (self, where, vars = None, ** kargs ): Db = _ connect_to_db () Try: With db. transaction (): Db. update (self. _ table_name (), where, vars, ** kargs) Except T (Exception) as e: Raise ModelError (str (e )) |