tutorial on using the Python web.py framework to implement a Django-like ORM query

Source: Internet
Author: User
Tags config vars

This article introduces a tutorial on using Python's web.py framework to implement a Django-like ORM query, and the integrated ORM Operations database has always been one of Python's most powerful features, and this article explores how to implement it in the web.py framework, and the friends you need can refer to the

Object Query in Django

The Django framework, with its own ORM, implements some of the more powerful and convenient query functions that have nothing to do with tables. For example, the following example:


1 2 3 4 5 6 7 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)

As can be seen from the example, Objects.all and objects.get These features are not defined in class question, possibly in their parent class models. Model, or maybe not. So how do we implement such a function in web.py? (If you choose to use sqlalchemy you don't need to implement it yourself).



We note that the invocation of Question.objects.all () is a direct access to the Class Property objects and invokes the method all () of the Objects property. Here objects may be an instance, or it may be a class. I personally think (I haven't seen the Django implementation) This should be an example, 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 of the parent-class model where the actual table can inherit from this parent class to obtain functionality that it does not define.

After the actual model class (such as the question Class) is defined, it is necessary to have a query effect such as Objects.all () without an instance.

As you can see from the above requirements, we need to implement these features when the class is defined, rather than wait until the class is instantiated to implement these features. What is the implementation of the function when the class is defined? This is not what metaclass (Meta Class) does. So the implementation process is probably the following:

Implementation of a model class, the binding method and table of the increase, delete, change related.

Modify the model class's meta class to Modelmetaclass, which is defined by adding a objects object to the class, which is an instance of a Modeldefaultmanager class that implements the query function of the table.


All say not to code is bullying, I still give it. Description: The database operations used are interfaces in the web.py DB Library.


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30-31 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 The 96 97 98 99 100 101 102 103 104 105 106 107 108 109 A #-*-coding:utf-8-*-  Import web   Import Config # 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.SQ L_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 Modeldefaultmanager (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 = _con nect_to_db () results = Db.select (self._table_name) return [Self.cls (x) for x into 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 (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 = Modeldefaultmanage R (New_class) setattr (New_class, "Objects", objects)   return New_class     class Model (object): "" "Parent C Lass of all models. "" "  __metaclass__ = Modelmetaclass   def __init__ (self): pass   def _table_name (self): return Self.__clas S__.__name__.lower ()   def insert (self, **kargs): db = _connect_to_db () try:with db.transaction (): Db.insert (self._ TABLE_NAME (), **kargs) except (Exception) as E:raise modelerror (str (e))   def delete (self, where, Using=none, vars=n One): Db = _connect_to_db () try:with db.transaction (): Db.delete (Self._table_name (), where, vars=vars) except (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 (Exception) as E:raise modelerror (str (e))


First, define the corresponding class for the table:


1 2 Class Users (Model): ...

Use the same way as Django:


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

Note < > : More Wonderful tutorials please focus on Triple programming

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.