Flask使用DBUtils模块连接数据库

Flask连接数据库
 
数据库连接池:
Django使用:django ORM(pymysql/MySqldb)
Flask/其他使用:
    -原生SQL
        -pymysql(支持python2/3)
        -MySqldb(支持python2)
    -SQLAchemy(ORM)
 
原生SQL
需要解决的问题:
        -不能为每个用户创建一个连接
        -创建一定数量的连接池,如果有人来
 
使用DBUtils模块
两种使用模式:
    1 为每个线程创建一个连接,连接不可控,需要控制线程数
    2 创建指定数量的连接在连接池,当线程访问的时候去取,如果不够了线程排队,直到有人释放。平时建议使用这种!!!
 
模式一:
 1 import pymysql
 2 from DBUtils.PersistentDB import PersistentDB
 3 
 4 POOL = PersistentDB(
 5     creator=pymysql,  # 使用链接数据库的模块
 6     maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制
 7     setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
 8     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
 9     closeable=False,
10     # 建议为False,如果为False时, conn.close() 实际上被忽略,供下次使用,再线程关闭时,才会自动关闭链接。如果为True时, conn.close()则关闭链接,那么再次调用pool.connection时就会报错,因为已经真的关闭了连接(pool.steady_connection()可以获取一个新的链接)
11     threadlocal=None,  # 本线程独享值得对象,用于保存链接对象,如果链接对象被重置
12     host='127.0.0.1',
13     port=3306,
14     user='root',
15     password='123',
16     database='pooldb',
17     charset='utf8'
18 )
19 
20 def func():
21     conn = POOL.connection(shareable=False)
22     cursor = conn.cursor()
23     cursor.execute('select * from tb1')
24     result = cursor.fetchall()
25     cursor.close()
26     conn.close()
27 
28 func()

模式二(推荐):

 1 import time
 2 import pymysql
 3 import threading
 4 from DBUtils.PooledDB import PooledDB, SharedDBConnection
 5 POOL = PooledDB(
 6     creator=pymysql,  # 使用链接数据库的模块
 7     maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数
 8     mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
 9     maxcached=5,  # 链接池中最多闲置的链接,0和None不限制
10     maxshared=3,  # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
11     blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
12     maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制
13     setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
14     ping=0,
15     # 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
16     host='127.0.0.1',
17     port=3306,
18     user='root',
19     password='123',
20     database='pooldb',
21     charset='utf8'
22 )
23 
24 
25 def func():
26     # 检测当前正在运行连接数的是否小于最大链接数,如果不小于则:等待或报raise TooManyConnections异常
27     # 否则
28     # 则优先去初始化时创建的链接中获取链接 SteadyDBConnection。
29     # 然后将SteadyDBConnection对象封装到PooledDedicatedDBConnection中并返回。
30     # 如果最开始创建的链接没有链接,则去创建一个SteadyDBConnection对象,再封装到PooledDedicatedDBConnection中并返回。
31     # 一旦关闭链接后,连接就返回到连接池让后续线程继续使用。
32     conn = POOL.connection()
33 
34     # print(th, '链接被拿走了', conn1._con)
35     # print(th, '池子里目前有', pool._idle_cache, '
')
36 
37     cursor = conn.cursor()
38     cursor.execute('select * from tb1')
39     result = cursor.fetchall()
40     conn.close()
41 
42 
43 func()
具体写法:
通过导入的方式
app.py
 1 from flask import Flask
 2 from db_helper import SQLHelper
 3 
 4 
 5 app = Flask(__name__)
 6 
 7 @app.route("/")
 8 def hello():
 9     result = SQLHelper.fetch_one('select * from xxx',[])
10     print(result)
11     return "Hello World"
12 
13 if __name__ == '__main__':
14     app.run()
 
DBUTILs
以下为两种写法:
第一种是用静态方法装饰器,通过直接执行类的方法来连接使用数据库
第二种是通过实例化对象,通过对象来调用方法执行语句
建议使用第一种,更方便,第一种还可以在修改优化为,将一些公共语句在摘出来使用。
 1 import time
 2 import pymysql
 3 from DBUtils.PooledDB import PooledDB
 4 POOL = PooledDB(
 5     creator=pymysql,  # 使用链接数据库的模块
 6     maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数
 7     mincached=2,  # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
 8     maxcached=5,  # 链接池中最多闲置的链接,0和None不限制
 9     maxshared=3,  # 链接池中最多共享的链接数量,0和None表示全部共享。PS: 无用,因为pymysql和MySQLdb等模块的 threadsafety都为1,所有值无论设置为多少,_maxcached永远为0,所以永远是所有链接都共享。
10     blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
11     maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制
12     setsession=[],  # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
13     ping=0,
14     # 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
15     host='127.0.0.1',
16     port=3306,
17     user='root',
18     password='123',
19     database='pooldb',
20     charset='utf8'
21 )
22 
23 """
24 class SQLHelper(object):
25     
26     @staticmethod
27     def fetch_one(sql,args):
28         conn = POOL.connection()
29         cursor = conn.cursor()
30         cursor.execute(sql, args)
31         result = cursor.fetchone()
32         conn.close()
33         return result
34 
35     @staticmethod
36     def fetch_all(self,sql,args):
37         conn = POOL.connection()
38         cursor = conn.cursor()
39         cursor.execute(sql, args)
40         result = cursor.fetchone()
41         conn.close()
42         return result
43     
44 # 调用方式:
45 result = SQLHelper.fetch_one('select * from xxx',[])
46 print(result)
47 """
48 
49 
50 """
51 #第二种:
52 class SQLHelper(object):
53 
54     def __init__(self):
55         self.conn = POOL.connection()
56         self.cursor = self.conn.cursor()
57 
58     def close(self):
59         self.cursor.close()
60         self.conn.close()
61 
62     def fetch_one(self,sql, args):
63         self.cursor.execute(sql, args)
64         result = self.cursor.fetchone()
65         self.close()
66         return result
67 
68 
69     def fetch_all(self, sql, args):
70         self.cursor.execute(sql, args)
71         result = self.cursor.fetchall()
72         self.close()
73         return result
74 
75 
76 obj = SQLHelper()
77 obj.fetch_one()
78 """
 
 
 
 
原文地址:https://www.cnblogs.com/ArmoredTitan/p/Flask.html