Use the Python web. py framework to implement a query tutorial similar to Django's ORM, web. pydjango

Source: Internet
Author: User

Use the Python web. py framework to implement a query tutorial similar to Django's ORM, web. pydjango

Query objects in Django

The Django framework comes with an ORM that provides powerful and convenient query functions. These functions are irrelevant to tables. For example:

class Question(models.Model):  question_text = models.CharField(max_length=200)  pub_date = models.DateTimeField('date published')>>> Question.objects.all()>>> Question.objects.get(pk=1)

From the example, we can see that objects. all and objects. get functions are not defined in class Question, and may be defined in its parent models. Model or not. So how can we implement this function in web. py? (If you choose to use SQLAlchemy, you do not need to implement it yourself ).
Implementation
Ideas

We noticed that the call like Question. objects. all () directly accesses the class attribute objects and calls the method all () of the objects attribute (). Here, objects may be an instance or a class. I personally think (I have never seen Django's implementation) this should be an instance, because the instantiation process can pass some table information so that functions like all () can work. After analysis, we can list the problems we need to solve:

  • You need to implement a Model's parent class Model. The actual table can inherit from this parent class to obtain features that are not defined by yourself.
  • After the actual model class (such as the Question class) is defined, the query results such as objects. all () should be available without an instance.
  • From the above requirements, we can see that we need to implement these functions when the class is defined, instead of waiting until the class is instantiated to implement these functions. When the class is defined? This is not what metaclass does. Therefore, the implementation process is as follows:
  • Implements a Model class. The binding method is related to table addition, deletion, and modification.
  • Modify the metadata class of the Model class to ModelMetaClass. Add an objects object to the class during the definition of the metaclass. This object is an instance of the modeldefamanager manager class and implements the Table query function.

Code

If you say no to the Code, it is just a rogue game. Let me give it. Note: The Database Operations used are interfaces in the db database of web. py.

#-*-Coding: UTF-8-*-import web import config # The custom configuration class can ignore 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) limit 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 = ModelDefaultManager (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 ))

Use

First, define the corresponding class of the table:

class Users(Model):  ...

The usage is the same as that of Django:

>>> user_list = Users.objects.all()

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.