Achieve orm

 
 
 
 
from my_signleton import MySignleton
# 字段类型的属性
class Field(object):
    def __init__(self,name,column_type,primary_key,default):
        self.name = name
        self.column_type = column_type
        self.primary_key = primary_key
        self.default = default
# 数字类型字段
class IntegerField(Field):
    def __init__(self,name,column_type="int",primary_key=False,default=0):
        super().__init__(name,column_type,primary_key,default)
# 字符串类型字段
class StringField(Field):
    def __init__(self,name,column_type="varchar(255)",primary_key=False,default=""):
        super().__init__(name,column_type,primary_key,default)
MyMetaClass class (of the type):
    DEF __new __ (CLS, class_name, class_bases, class_attrs):
        # We want to block the process of creating the model table, and the following Model does not need to intercept, so do first layer to determine
        if class_name == "Model ":
            return of the type .__ new new __ (class_name, class_bases, class_attrs)
        # first, we want to get a table name, the primary key field names, other field name
        table_name = class_attrs.get (" table_name ")
        primary_key = None
        Mappings = {}
        for k, in class_attrs.items v ():
            # judged are above field object
            IF isinstance (v, field,):
                # determine the primary key object
                IF v.primary_key:
                    # If there is already a primary key would report a mistake
                    if primary_key:
                        raise TypeError ( "only by a primary key")
                    primary_key = V
                # rest is other fields, all added to the mappings
                mappings [k] = v
        after # remove all field objects, class_attrs are no longer necessary, and to deleted
        for k in mappings.keys ():
            class_attrs.pop (k)
        # If a pass down the operation or not a primary key, you throw these exceptions
        IF not primary_key:
            the raise TypeError ( "must have a primary key")
        # next to us to obtain several properties (table_name, primary_key, mappings) added to the name space (class_attrs) in
        class_attrs [ "table_name"] = table_name
        class_attrs [ "primary_key"] = primary_key
        class_attrs [ "Mappings"] = Mappings
        # final call type in the new method
        return type.__new__(class_name,class_bases,class_attrs)
# Design of a model class, substitution tables may
# (can point out properties, the properties may be set points, may also be instantiated variable length brackets pass generation target)
# parameters regardless of how much mass can instantiate an object class reference dictionary we want to use this method needs to inherit only dictionary class
class Model (dict, the metaclass that = MyMetaClass):
    # print out the class dictionary is a dictionary although there are key-value pairs
    # but
 
 

Singleton

import pymysql
# I would need to define a class, let me call orm produce objects
# then I put on the inside of his method and database operations correspond to
# connect to the database and database objects generated operating the Cursor
conn = pymysql.connect (Host = " localhost ", User =" the root ", password =" hsjqqq ", charset =" UTF8 ",
                      Database =" the youku ", the autocommit = True)
Cursor = conn.cursor (pymysql.cursors.DictCursor)
MySingleton class (Object):
    _instence = None
    # write directly connected to the init process, so long as the resulting objects will be connected to the database
    # introduced instead of a connection to the database module will
    DEF the __init __ (Self):
        self.conn = pymysql. Connect (
            Host = "localhost", User = "the root", password = "hsjqqq", charset = "UTF8",
            Database = "the youku", the autocommit = True
        )
        self.cursor = self.conn.cursor (pymysql.cursors. DictCursor)
    # pass over sql statement and need to pass parameters (to prevent sql injection)
    DEF the SELECT (Self, sql, arg = None):
        # the Execute (Self, Query, args = None): this function already has a arg default None
        # so no matter arg has no traditional values, we can get lost in the past, execute
        self.cursor.execute (sql, arg)
        = self.cursor.fetchall back_list ()
        return back_list # returns a list of all queries to the dictionary of
    Save DEF (Self, SQL, args):
        the try:
            self.cursor.execute (SQL, args)
        the except Exception AS E:
            Print (E)
    # in order to prevent each of the objects take to generate a memory address to open up a space, here we use single embodiment mode
    @classmethod
    DEF SINGLE (CLS):
        # variable is used to give a presence of an object class is generated,
        # if the object can not be found, then this table is the first target to produce
        IF Not cls._instence:
            CLS. CLS = _instence ()
        # then every time they want to create an object, I just want to pick up this variable to
        return cls._instence
singletion
 
 
 

Thread pool version

from DBUtils.PooledDB import PooledDB
import pymysql
= PooledDB the POOL (
    Creator = pymysql, link database module #
    maxconnections = 6, the maximum number of connections permitted by the connection pool # 0 and not to limit the number of connections None
    mincached = 2, when the # initialization, idle pool to create at least a link link, 0 does not create
    maxcached = 5, the largest pool of idle links # links, 0 and None not limit
    maxshared = 3,
    the number of links up to a shared pool of links # 0 and None represent all share .PS: useless, because threadsafety pymysql and MySQLdb modules are 1, all values regardless of the setting for the number, _maxcached is always 0, so that all links are always shared.
    blocking = True, # connection pool If there is no available connection, whether block waiting. True, wait; False, then do not wait for an error
    maxusage = None, # a number of links up to be reused, None means unlimited
    setsession = [], a list of commands that are executed before the start of the session as #: [ "set datestyle to.. .. "," Time Zone SET ... "]
    of ping = 0,
    # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
    host='127.0.0.1',
    port=3306,
    user='root',
    password='hsjqqq',
    database='youku',
    charset='utf8',
    autocommit='True'
)
MySingleton class (Object):
    _instence = None
    # write directly connected to the init process, so long as the resulting objects will be connected to the database
    # introduced instead of a connection to the database module will
    DEF the __init __ (Self):
        self.conn = the POOL. Connection ()
        self.cursor = self.conn.cursor (pymysql.cursors.DictCursor)
    # Pass over sql statement and need to pass parameters (to prevent sql injection)
    DEF the SELECT (Self, sql, arg = None):
        # the Execute (Self, Query, args = None): This function already has a default arg None
        # so no matter arg has no traditional values, we can get lost in the past, execute
        self.cursor.execute (SQL, arg)
        back_list = self.cursor.fetchall ()
        return back_list # returns a list of all queries to the dictionary of
    def save(self,sql,args):
        try:
            self.cursor.execute(sql,args)
        except Exception as e:
            print(e)
single_pool
 
 

Guess you like

Origin www.cnblogs.com/huikejie/p/11112193.html