How to Use the Python web. py framework to implement a Django-like ORM query tutorial

Source: Internet
Author: User
Tags vars

How to Use the Python web. py framework to implement a Django-like ORM query tutorial

This article mainly introduces the web using Python. the py framework implements a query tutorial similar to Django's ORM. The integrated ORM operation database has always been one of the most powerful functions of Python. This article will discuss how to use it on the web. for more information about the implementation of the py framework, see

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:

?

1

2

3

4

5

6

7

Class Question (models. Model ):

Question_text = models. CharField (max_length = 200)

Pub_date = models. DateTimeField ('date hhed ')

 

 

>>> 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.

?

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

32

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

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

#-*-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 ))

Use

First, define the corresponding class of the table:

?

1

2

Class Users (Model ):

...

The usage is the same as that of Django:

?

1

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

Note <>: For more exciting tutorials, please pay attention to the help house programming

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.