63 lines
1.6 KiB
Python
63 lines
1.6 KiB
Python
#!/usr/bin/env python3
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
数据库连接池模块
|
|
"""
|
|
import pymysql
|
|
from dbutils.pooled_db import PooledDB
|
|
from flask import current_app
|
|
|
|
# 全局连接池
|
|
_pool = None
|
|
|
|
def get_pool():
|
|
"""获取数据库连接池"""
|
|
global _pool
|
|
if _pool is None:
|
|
_pool = PooledDB(
|
|
creator=pymysql,
|
|
maxconnections=20,
|
|
mincached=2,
|
|
maxcached=5,
|
|
blocking=True,
|
|
ping=1,
|
|
host=current_app.config['DB_HOST'],
|
|
port=current_app.config['DB_PORT'],
|
|
user=current_app.config['DB_USER'],
|
|
password=current_app.config['DB_PASSWORD'],
|
|
database=current_app.config['DB_NAME'],
|
|
charset='utf8mb4',
|
|
cursorclass=pymysql.cursors.DictCursor
|
|
)
|
|
return _pool
|
|
|
|
def get_connection():
|
|
"""获取数据库连接"""
|
|
return get_pool().connection()
|
|
|
|
def init_db(app):
|
|
"""初始化数据库连接池"""
|
|
global _pool
|
|
with app.app_context():
|
|
_pool = PooledDB(
|
|
creator=pymysql,
|
|
maxconnections=20,
|
|
mincached=2,
|
|
maxcached=5,
|
|
blocking=True,
|
|
ping=1,
|
|
host=app.config['DB_HOST'],
|
|
port=app.config['DB_PORT'],
|
|
user=app.config['DB_USER'],
|
|
password=app.config['DB_PASSWORD'],
|
|
database=app.config['DB_NAME'],
|
|
charset='utf8mb4',
|
|
cursorclass=pymysql.cursors.DictCursor
|
|
)
|
|
|
|
def close_db():
|
|
"""关闭数据库连接池"""
|
|
global _pool
|
|
if _pool is not None:
|
|
_pool.closeAll()
|
|
_pool = None |