A, ORM
Before we are to save the file format for storing data, this time we are using a combination of database use python, used
ORM: Relational Mapping
Class "" a database table
Object "" table a record
Object attribute "," record a value corresponding to a field
About ORM fact, we can call someone else has written, this time we write your own ORM.
This is to call someone else's written in Django
1. First design field type (this will only use two field types, only two design)
Field: field names, field types, whether the primary key, default value
# Define field type name, column_type, primary_key, default (field names, field types, primary key, the default value) class Field, (Object): DEF the __init__ (Self, name, column_type, primary_key, default): the self.name = name Self. column_type = column_type self.primary_key = primary_key self.default = default # the following types may not be defined, but every time you call field when each parameter value needs to write # define varchar field type (for in field type is varchar a) class StringField (Field,): DEF the __init__ (Self, name, column_type = ' VARCHAR (32) ',primary_key = False,default = None): super().__init__(name,column_type,primary_key,default) #定义int字段类型 class IntegerField(Field): def __init__(self,name,column_type = 'int',primary_key =False ,default = 0): super().__init__(name,column_type,primary_key,default)
2. Design model table
Inherit a dictionary, you can receive an arbitrary number of keyword arguments
All model table inherit Models, Models inherit dict, __ getattr__ when the value via the object. The way property, the property does not exist, this method will trigger
__setattr__ when new or modify the properties of this method is triggered when
class Models (dict, the metaclass that = Mymetaclass) DEF the __init__ (Self, kwargs **): # receiving a plurality of key parameters of any Super (). the __init__ (** kwargs) # Inherited dict DEF __getattr__ (Self, Item): # Item is the name of self attribute that does not exist is a dictionary object return self.get (Item) DEF __setattr__ (self, Key, value): # add or modify the properties will take this self [Key] = value
3. Use metaclass, intercepted the process of creating a custom table model
Use meta class, the class created when the table name, field, primary key class superimpose
In three steps to create a class:
1 .__ new__ generates an empty object
2 .__ init__ instantiated
3. The resulting object is returned
class MyMetaclass (of the type): # need to set the table name, primary key, field DEF __new__ (CLS, class_name, class_bases, class_attr): # __new__ create an empty object, class_name (class name), class_bases (base classes are), class_attr ( namespace) # custom metaclass is to create a process model to intercept the table, while not a model table models, so it does not require the creation IF class_name == ' models ' : return . of the type __new__ (CLS, class_name, class_bases , class_attr) # If models direct return of the type table_name = class_attr.get ( ' table_name ' , class_name) # get the table name in the namespace, class name is not returned primary_key = None Mappings} = { # Convenient later value for K, V in class_attr.items (): # cycles get all key name space for k: id, name v: IntegerField (), StringField () object IF the isinstance (V, field,): # take out all the custom field attribute # all fields from the definition table stored in the dictionary all Mappings [K] = V iF v.primary_key: # determines whether there is a primary key field iF primary_key: the raise TypeError ( ' a tables only one master key ' ) primary_key = V.NAME # set the primary key field name #Cycle out mappings of key (that is, a custom field name), as defined mappings from behind should put class_attr inside, so to save space key to delete the original for k in mappings.keys (): class_attr. POP (k) # repeated k within the namespace, v deletion key # checking whether the custom table primary key field specifies the iF Not primary_key: the raise TypeError ( ' a table must have a primary key ' ) class_attr [ ' table_name ' ] = table_name class_attr [ ' primary_key ' ] = primary_key class_attr [ ' Mappings ' ] = Mappings return type.__new__(cls,class_name,class_bases,class_attr)
4. pymsql binding modules, package the query statements and submitting
import pymysql from orm.db_pool import POOL class Mysql: def __init__(self): self.conn =POOL.connection() self.cursor = self.conn.cursor(pymysql.cursors.DictCursor) #创建游标 def close_db(self): self.cursor.close() self.conn.close() #查询 def select(self,sql,args = None): self.cursor.execute(sql,args) res = self.cursor.fetchall() #查询所有 [{},{},{}....] return res #封装提交 def myexecute(self,sql,args): try: self.cursor.execute(sql,args) except Exception as e: print(e)
Second, the project writing
Project by the service and client composition, socket-based communications
Unfinished