You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask应用如何在create_app中一次性创建cx_Oracle会话池并在路由使用

问题1解答:原有初始化方式不正确

你当前的写法只是调用函数生成了连接池实例,但没有对实例做持久化存储,函数执行完成后实例就被回收了,完全达不到后续复用的目的。另外你不需要额外套with app.app_context()代码块,连接池初始化方法可以直接接收app实例读取配置,稳定性更高。

问题2解答:连接池复用实现方案

我们通过「模块级变量存储连接池+封装初始化/获取方法」的方式实现全局复用,只需修改3处代码即可:

1. 修改 simple_app/lib/oracle.py

import cx_Oracle

# 模块级全局变量存储连接池实例
_pool = None

def init_pool(app):
    """应用启动时调用,初始化Oracle连接池"""
    global _pool
    if _pool is None:
        _pool = cx_Oracle.SessionPool(
            user=app.config['USER'],
            password=app.config['PASSWD'],
            dsn=app.config['DSN'],
            min=4,
            max=10,
            increment=1,
            threaded=True,
            getmode=cx_Oracle.SPOOL_ATTRVAL_WAIT
        )

def get_pool():
    """路由中调用,获取全局连接池实例"""
    return _pool

2. 修改 simple_app/__init__.py

from flask import Flask
from flask_cors import CORS

from .lib.oracle import init_pool
from .routes import init_app as init_routes

def create_app():
    app = Flask(__name__)
    CORS(app)
    app.secret_key = 'dev'
    app.config.from_object('configSIMPLE')

    # 初始化Oracle连接池
    init_pool(app)
    # 注册路由
    init_routes(app)
    return app

3. 修改 simple_app/routes/oracle_pdb_backup.py

from flask import Blueprint, jsonify
from ..lib.oracle import get_pool

oracle_pdb_backup_bp = Blueprint('oracle_pdb_backup', __name__)

@oracle_pdb_backup_bp.route('/oracle/pdb/backup', methods=['GET'])
def oracle_pdb_backup_post():
    # 获取全局连接池实例
    pool = get_pool()
    # 从池中获取连接
    connection = pool.acquire()
    # 使用池化连接
    cursor = connection.cursor()
    cursor.execute('select * from dual')
    result = cursor.fetchall()
    cursor.close()
    # 将连接释放回池
    pool.release(connection)
    return jsonify(message = result), 200

额外注意事项

如果后续你改用多进程部署(比如Gunicorn启动多个worker),每个进程会独立创建一个连接池,需要注意调整池的最大连接数,避免总连接数超过Oracle数据库的上限。

内容的提问来源于stack exchange,提问作者Laurent D.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 21:48:00