DBUtils是Python的一个用于实现数据库链接池的模块。python
此链接池有两种链接模式:mysql
POOL = PersistentDB( creator=pymysql, # 使用连接数据库的模块 maxusage=None, # 一个连接最多被重复使用的次数,None表示无限制 setsession=[], # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."] 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 closeable=False, # 若是为False时, conn.close() 实际上被忽略,供下次使用,再线程关闭时,才会自动关闭连接。若是为True时, conn.close()则关闭连接,那么再次调用pool.connection时就会报错,由于已经真的关闭了链接(pool.steady_connection()能够获取一个新的连接) threadlocal=None, # 本线程独享值得对象,用于保存连接对象,若是连接对象被重置 host='127.0.0.1', port=3306, user='root', password='123', database='pooldb', charset='utf8' ) def func(): conn = POOL.connection(shareable=False) cursor = conn.cursor() cursor.execute('select * from tb1') result = cursor.fetchall() cursor.close() conn.close() func()
PS:因为pymysql、MySQLdb等threadsafety值为1,因此该模式链接池中的线程会被全部线程共享。redis
import time import pymysql import threading from DBUtils.PooledDB import PooledDB, SharedDBConnection POOL = PooledDB( creator=pymysql, # 使用连接数据库的模块 maxconnections=6, # 链接池容许的最大链接数,0和None表示不限制链接数 mincached=2, # 初始化时,连接池中至少建立的空闲的连接,0表示不建立 maxcached=5, # 连接池中最多闲置的连接,0和None不限制 maxshared=3, # 连接池中最多共享的连接数量,0和None表示所有共享。PS: 无用,由于pymysql和MySQLdb等模块的 threadsafety都为1,全部值不管设置为多少,_maxcached永远为0,因此永远是全部连接都共享。 blocking=True, # 链接池中若是没有可用链接后,是否阻塞等待。True,等待;False,不等待而后报错 maxusage=None, # 一个连接最多被重复使用的次数,None表示无限制 setsession=[], # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."] 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='123', database='pooldb', charset='utf8' ) def func(): # 检测当前正在运行链接数的是否小于最大连接数,若是不小于则:等待或报raise TooManyConnections异常 # 不然 # 则优先去初始化时建立的连接中获取连接 SteadyDBConnection。 # 而后将SteadyDBConnection对象封装到PooledDedicatedDBConnection中并返回。 # 若是最开始建立的连接没有连接,则去建立一个SteadyDBConnection对象,再封装到PooledDedicatedDBConnection中并返回。 # 一旦关闭连接后,链接就返回到链接池让后续线程继续使用。 conn = POOL.connection() # print(th, '连接被拿走了', conn1._con) # print(th, '池子里目前有', pool._idle_cache, '\r\n') cursor = conn.cursor() cursor.execute('select * from tb1') result = cursor.fetchall() conn.close() func()
flask中是没有ORM的,若是在flask里面链接数据库有两种方式sql
一:pymysql 二:SQLAlchemy 是python 操做数据库的一个库。可以进行 orm 映射官方文档 sqlchemy SQLAlchemy“采用简单的Python语言,为高效和高性能的数据库访问设计,实现了完整的企业级持久模型”。SQLAlchemy的理念是,SQL数据库的量级和性能重要于对象集合;而对象集合的抽象又重要于表和行。
连接池原理数据库
- BDUtils数据库连接池 - 模式一:基于threaing.local实现为每个线程建立一个链接,关闭是 伪关闭,当前线程能够重复 - 模式二:链接池原理 - 能够设置链接池中最大链接数 9 - 默认启动时,链接池中建立链接 5 - 若是有三个线程来数据库中获取链接: - 若是三个同时来的,一人给一个连接 - 若是一个一个来,有时间间隔,用一个连接就能够为三个线程提供服务 - 说不许 有可能:1个连接就能够为三个线程提供服务 有可能:2个连接就能够为三个线程提供服务 有可能:3个连接就能够为三个线程提供服务 PS、:maxshared在使用pymysql中均无用。连接数据库的模块:只有threadsafety>1的时候才有用
那么咱们用pymysql来作。flask
为何要使用数据库链接池呢?不用链接池有什么很差的地方呢?session
方式1、每次操做都要连接数据库,连接次数过多多线程
#!usr/bin/env python # -*- coding:utf-8 -*- import pymysql from flask import Flask app = Flask(__name__) # 方式一:这种方式每次请求,反复建立数据库连接,屡次连接数据库会很是耗时 # 解决办法:放在全局,单例模式 @app.route('/index') def index(): # 连接数据库 conn = pymysql.connect(host="127.0.0.1",port=3306,user='root',password='123', database='pooldb',charset='utf8') cursor = conn.cursor() cursor.execute("select * from td where id=%s", [5, ]) result = cursor.fetchall() # 获取数据 cursor.close() conn.close() # 关闭连接 print(result) return "执行成功" if __name__ == '__main__': app.run(debug=True)
方式2、不支持并发并发
#!usr/bin/env python # -*- coding:utf-8 -*- import pymysql from flask import Flask from threading import RLock app = Flask(__name__) CONN = pymysql.connect(host="127.0.0.1",port=3306,user='root',password='123', database='pooldb',charset='utf8') # 方式二:放在全局,若是是单线程,这样就能够,可是若是是多线程,就得加把锁。这样就成串行的了 # 不支持并发,也很差。全部咱们选择用数据库链接池 @app.route('/index') def index(): with RLock: cursor = CONN.cursor() cursor.execute("select * from td where id=%s", [5, ]) result = cursor.fetchall() # 获取数据 cursor.close() print(result) return "执行成功" if __name__ == '__main__': app.run(debug=True)
方式三:因为上面两种方案都不完美,因此得把方式一和方式二联合一下(既让减小连接次数,也能支持并发)全部了方式三,须要app
导入一个DButils模块
基于DButils实现的数据库链接池有两种模式:
模式一:为每个线程建立一个连接(是基于本地线程来实现的。thread.local),每一个线程独立使用本身的数据库连接,该线程关闭不是真正的关闭,本线程再次调用时,仍是使用的最开始建立的连接,直到线程终止,数据库连接才关闭
注: 模式一:若是线程比较多仍是会建立不少链接,模式二更经常使用
#!usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask app = Flask(__name__) from DBUtils.PersistentDB import PersistentDB import pymysql POOL = PersistentDB( creator=pymysql, # 使用连接数据库的模块 maxusage=None, # 一个连接最多被重复使用的次数,None表示无限制 setsession=[], # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."] 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 closeable=False, # 若是为False时, conn.close() 实际上被忽略,供下次使用,再线程关闭时,才会自动关闭连接。若是为True时, conn.close()则关闭连接,那么再次调用pool.connection时就会报错,由于已经真的关闭了链接(pool.steady_connection()能够获取一个新的连接) threadlocal=None, # 本线程独享值得对象,用于保存连接对象,若是连接对象被重置 host='127.0.0.1', port=3306, user='root', password='123', database='pooldb', charset='utf8' ) @app.route('/func') def func(): conn = POOL.connection() cursor = conn.cursor() cursor.execute('select * from tb1') result = cursor.fetchall() cursor.close() conn.close() # 不是真的关闭,而是假的关闭。 conn = pymysql.connect() conn.close() conn = POOL.connection() cursor = conn.cursor() cursor.execute('select * from tb1') result = cursor.fetchall() cursor.close() conn.close() if __name__ == '__main__': app.run(debug=True)
模式二:建立一个连接池,为全部线程提供链接,使用时来进行获取,使用完毕后在放回到链接池。
PS:假设最大连接数有10个,其实也就是一个列表,当你pop一个,人家会在append一个,连接池的全部的连接都是按照排队的这样的方式来连接的。
连接池里全部的连接都能重复使用,共享的, 即实现了并发,又防止了连接次数太多
import time import pymysql import threading from DBUtils.PooledDB import PooledDB, SharedDBConnection POOL = PooledDB( creator=pymysql, # 使用连接数据库的模块 maxconnections=6, # 链接池容许的最大链接数,0和None表示不限制链接数 mincached=2, # 初始化时,连接池中至少建立的空闲的连接,0表示不建立 maxcached=5, # 连接池中最多闲置的连接,0和None不限制 maxshared=3, # 连接池中最多共享的连接数量,0和None表示所有共享。PS: 无用,由于pymysql和MySQLdb等模块的 threadsafety都为1,全部值不管设置为多少,_maxcached永远为0,因此永远是全部连接都共享。 blocking=True, # 链接池中若是没有可用链接后,是否阻塞等待。True,等待;False,不等待而后报错 maxusage=None, # 一个连接最多被重复使用的次数,None表示无限制 setsession=[], # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."] 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='123', database='pooldb', charset='utf8' ) def func(): # 检测当前正在运行链接数的是否小于最大连接数,若是不小于则:等待或报raise TooManyConnections异常 # 不然 # 则优先去初始化时建立的连接中获取连接 SteadyDBConnection。 # 而后将SteadyDBConnection对象封装到PooledDedicatedDBConnection中并返回。 # 若是最开始建立的连接没有连接,则去建立一个SteadyDBConnection对象,再封装到PooledDedicatedDBConnection中并返回。 # 一旦关闭连接后,链接就返回到链接池让后续线程继续使用。 # PooledDedicatedDBConnection conn = POOL.connection() # print(th, '连接被拿走了', conn1._con) # print(th, '池子里目前有', pool._idle_cache, '\r\n') cursor = conn.cursor() cursor.execute('select * from tb1') result = cursor.fetchall() conn.close() conn = POOL.connection() # print(th, '连接被拿走了', conn1._con) # print(th, '池子里目前有', pool._idle_cache, '\r\n') cursor = conn.cursor() cursor.execute('select * from tb1') result = cursor.fetchall() conn.close() func()
使用时咱们能够将数据库链接池写到配置文件中
from datetime import timedelta from redis import Redis import pymysql from DBUtils.PooledDB import PooledDB, SharedDBConnection class Config(object): DEBUG = True SECRET_KEY = "umsuldfsdflskjdf" PERMANENT_SESSION_LIFETIME = timedelta(minutes=20) SESSION_REFRESH_EACH_REQUEST= True SESSION_TYPE = "redis" PYMYSQL_POOL = PooledDB( creator=pymysql, # 使用连接数据库的模块 maxconnections=6, # 链接池容许的最大链接数,0和None表示不限制链接数 mincached=2, # 初始化时,连接池中至少建立的空闲的连接,0表示不建立 maxcached=5, # 连接池中最多闲置的连接,0和None不限制 maxshared=3, # 连接池中最多共享的连接数量,0和None表示所有共享。PS: 无用,由于pymysql和MySQLdb等模块的 threadsafety都为1,全部值不管设置为多少,_maxcached永远为0,因此永远是全部连接都共享。 blocking=True, # 链接池中若是没有可用链接后,是否阻塞等待。True,等待;False,不等待而后报错 maxusage=None, # 一个连接最多被重复使用的次数,None表示无限制 setsession=[], # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."] 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='123456', database='s8day127db', charset='utf8' )
而后写一个类来帮咱们完成pymql的操做
import pymysql from settings import Config class SQLHelper(object): @staticmethod def open(cursor): POOL = Config.PYMYSQL_POOL conn = POOL.connection() cursor = conn.cursor(cursor=cursor) return conn,cursor @staticmethod def close(conn,cursor): conn.commit() cursor.close() conn.close() @classmethod def fetch_one(cls,sql,args,cursor =pymysql.cursors.DictCursor): conn,cursor = cls.open(cursor) cursor.execute(sql, args) obj = cursor.fetchone() cls.close(conn,cursor) return obj @classmethod def fetch_all(cls,sql, args,cursor =pymysql.cursors.DictCursor): conn, cursor = cls.open(cursor) cursor.execute(sql, args) obj = cursor.fetchall() cls.close(conn, cursor) return obj
而后在视图函数中就可使用这个类来进行数据库操做了
obj = SQLHelper.fetch_one('select id from users where name=%s',[field.data,])
一、子类继承父类的三种方式
class Dog(Animal): #子类 派生类 def __init__(self,name,breed, life_value,aggr): # Animal.__init__(self,name,breed, life_value,aggr)#让子类执行父类的方法 就是父类名.方法名(参数),连self都得传 super().__init__(name,life_value,aggr) #super关键字 ,都不用传self了,在新式类里的 # super(Dog,self).__init__(name,life_value,aggr) #上面super是简写 self.breed = breed def bite(self,person): #狗的派生方法 person.life_value -= self.aggr def eat(self): #父类方法的重写 super().eat() print('dog is eating')
二、对象经过索引设置值的三种方式
方式一:重写__setitem__方法
class Foo(object): def __setitem__(self, key, value): print(key,value) obj = Foo() obj["xxx"] = 123 #给对象赋值就会去执行__setitem__方法
方式二:继承dict
class Foo(dict): pass obj = Foo() obj["xxx"] = 123 print(obj)
方式三:继承dict,重写__init__方法的时候,记得要继承父类的__init__方法
class Foo(dict): def __init__(self,val): # dict.__init__(self, val)#继承父类方式一 # super().__init__(val) #继承父类方式二 super(Foo,self).__init__(val)#继承父类方式三 obj = Foo({"xxx":123}) print(obj)
总结:若是遇到obj["xxx"] = xx ,
- 重写了__setitem__方法 - 继承dict
三、测试__name__方法
示例:
app1中: import app2 print('app1', __name__) app2中: print('app2', __name__)
如今app1是主程序,运行结果截图
总结:若是是在本身的模块中运行,__name__就是__main__,若是是从别的文件中导入进来的,就不是__name__了
==========方式一:============ app.config['SESSION_COOKIE_NAME'] = 'session_lvning' #这种方式要把全部的配置都放在一个文件夹里面,看起来会比较乱,因此选择下面的方式 ==========方式二:============== app.config.from_pyfile('settings.py') #找到配置文件路径,建立一个模块,打开文件,并获取全部的内容,再将配置文件中的全部值,都封装到上一步建立的配置文件模板中 print(app.config.get("CCC")) =========方式三:对象的方式============ import os os.environ['FLAKS-SETTINGS'] = 'settings.py' app.config.from_envvar('FLAKS-SETTINGS') ===============方式四(推荐):字符串的方式,方便操做,不用去改配置,直接改变字符串就好了 ============== app.config.from_object('settings.DevConfig') ----------settings.DevConfig---------- from app import app class BaseConfig(object): NNN = 123 #注意是大写 SESSION_COOKIE_NAME = "session_sss" class TestConfig(BaseConfig): DB = "127.0.0.1" class DevConfig(BaseConfig): DB = "52.5.7.5" class ProConfig(BaseConfig): DB = "55.4.22.4"
要想在视图函数中获取配置文件的值,都是经过app.config来拿。可是若是视图函数和Flask建立的对象app不在一个模块。就得
导入来拿。能够不用导入,。直接导入一个current_app,这个就是当前的app对象,用current_app.config就能查看到了当前app的全部的配置文件
from flask import Flask,current_app @app.route('/index',methods=["GET","POST"]) def index(): print(current_app.config) #当前的app的全部配置 session["xx"] = "fdvbn" return "index"