In the previous article we introduced more or less about
Pythonof knowledge, and to be in combat, we will use
Python Development page, in fact, with
Framework Development Page, is the simplest and the most relaxed. In this chapter, we will introduce
Python page DevelopmentIn the use of
ORM Framework
Development page.
What is ORM
ORM is the object relational Mapping, the full name of a relational mapping.
But what exactly does it do?
If exposed to some of the Web backend, we know that a large part of the Web backend work is to add and delete data, if each operation of the database to connect to the database, construct SQL statements, execute SQL statements, it is too troublesome, so we can put the database table, fields, rows, With our object-oriented programming classes, classes of properties, and objects to establish a mapping relationship one by one, so that we can avoid the direct operation of the database, as long as the corresponding method is called.
Take my past practice for example to understand, such as the implementation of a user registration, how I did before, the front desk to get data, passed to the background, and then the background string concatenation form SQL statement, the background execution.
With the ORM , I just need to instantiate a user object with the data, and then call the object's Save method, then save to the database, as a user's perspective, do not need to manipulate an SQL statement.
Suppose the user class corresponds to the Users table
User=user (id= "100001", name= "Andy", password= "* * * *") User.save () //Save to Database User=user.findbyid ("100001") # Find User User.update (password= "*********") with id "100001" from the database and user password for "100001" #更改id为 Users=user.findall () # Remove all data from the users table
I asked, is it uncomfortable to use?
Attention
The IO operation is asynchronous and the asynchronous library used is Asyncio
Linked database for MySQL 5.7, MySQL asynchronous IO driver for Aiomysql
The necessary preparation for implementing ORM---encapsulating database operations
Create a database connection pool
Import Asyncioimport aiomysql async def create_pool (**kw): Global __pool__pool=await Aiomysql.create_pool ( Host=kw.get (' host ', ' localhost '), port=kw.get (' Port ', 3306), user=kw[' user '], password=kw[' password ' ], db=kw[' db '], charset=kw.get (' CharSet ', ' UTF8 '), autocommit=kw.get (' autocommit ', True), # autocommit transaction maxsize=kw.get (' MaxSize ', ten), # 10 linked objects in the pool (' MinSize ', 1), and up to a maximum of minsize=kw.get)
Encapsulating the Select method
Async def Select (sql,args,size=none)://size can decide to take several global __poolwith (await __pool) as Conn: cur=await conn.cursor ( Aiomysql. dictcursor) # Replace with parameters instead of string concatenation to prevent SQL injection await Cur.execute (Sql.replace ('? ', '%s '), args) if size: rs= Await Cur.fetchmany (size) else: rs=await cur.fetchall () await Cur.close () return RS
In addition to the Select method to return the query content, the remaining update,insert,delete only need to return an impact row number, so they can be three encapsulated as an Execute method
def execute (Sql,args): Global __pooltry: With (await __pool) as Conn: cur=await conn.cursor () await Cur.execute (Sql.replace ('? ', '%s '), args) affected=cur.rowcount await cur.close () except Baseexception as E : Raise Ereturn affected
Start implementing ORM
There is a thought in programming called "Top-down". So when you don't know how to design an orm , you can assume that you already have an ORM framework , how do you want to use it?
Class Model (object): async def find (self): passclass User (Model): # Note Here are the class properties __table__= "Users" Id=stringfield (...) Name=stringfield (...) User=user (id= "10001", Name= "Andy") User.save ()
There is no discovery, so look at the user class, very clear, corresponding to the user table, the table has what fields, at a glance. Then let the subclass inherit the parent class and implement the Find,save ... and other methods of reuse. It's perfect, but how do you do it?
Implementation of the field class
Class field (object): def __init__ (self,name,column_type,primary_key,default): self.name=name # field name Self.column_type=column_type # field Data type Self.primary_key=primary_key # is the primary key Self.default=default # There is no default value def __str__ (self): return ' <%s:%s> '% (self.__class__.__name__,self.name) class Stringfield (Field): def __init__ (self,name=none,primary_key=false,default=none,ddl= ' varchar): Super ( stringfield,self). __init__ (Name,ddl,primary_key,default) # Other words paragraphs, a truth, a pattern