python - Flask:如何在路由(其他 .py 文件)的 __init.py__.create_app() 中使用创建一次的 cx_Oracle.SessionPool
问题描述
我有一个像这样的简单 Flask 应用程序:
simple_app/lib/oracle.py:
import cx_Oracle
from flask import current_app
def create_pool():
# Create session pool
pool = cx_Oracle.SessionPool(user=current_app.config['USER'],
password=current_app.config['PASSWD'],
dsn=current_app.config['DSN'],
min=4,
max=10,
increment=1,
threaded=True,
getmode=cx_Oracle.SPOOL_ATTRVAL_WAIT)
return pool
simple_app/routes/ init .py:
from .hello import hello_bp
from .oracle_pdb_backup import oracle_pdb_backup_bp
def init_app(app):
app.register_blueprint(hello_bp)
app.register_blueprint(oracle_pdb_backup_bp)
simple_app/routes/hello.py:
from flask import Blueprint, jsonify
hello_bp = Blueprint('hello', __name__)
@hello_bp.route('/hello', methods=['GET'])
def hello_get():
return jsonify(message = f'hello world!'), 200
simple_app/routes/oracle_pdb_backup.py:
from flask import Blueprint, jsonify
from ..lib.oracle import *
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 = ?????? how to access pool defined at app creation ??????
# Acquire a connection from the pool
connection = pool.acquire()
# Use the pooled connection
cursor = connection.cursor()
cursor.execute('select * from dual')
result = cursor.fetchall()
cursor.close()
# Release the connection to the pool
db_pool.release(connection)
return jsonify(message = result), 200
简单应用程序/初始化.py:
from flask import Flask
from flask_cors import CORS
from .lib.oracle import *
from .routes import *
def create_app():
app = Flask(__name__)
CORS(app)
app.secret_key = 'dev'
app.config.from_object('configSIMPLE')
with app.app_context():
create_pool()
routes.init_app(app)
return app
我使用以下命令启动应用程序:
export PATH=~/python3/bin:$PATH
export LD_LIBRARY_PATH=~/instantclient_19_12
cd ~/myapps
export FLASK_RUN_HOST=`hostname`
export FLASK_RUN_PORT=8080
export FLASK_APP=simple_app
export FLASK_ENV=development
export FLASK_DEBUG=1
flask run
如何在 create_app() 中创建一次 cx_Oracle.SessionPool 并在我的所有路由中使用它
注意:池是在 simple_app/lib/oracle.py 的 create_pool() 函数中创建的
首先,我不知道是否:
with app.app_context():
create_pool()
是在创建应用程序时初始化池的正确方法吗?
其次,如何在我的路线中使用创建的池?
请参阅 simple_app/routes/oracle_pdb_backup.py 中的以下行:
pool = ?????? how to access pool defined at app creation ??????
你能告诉我我应该修改什么以使其工作吗?
感谢您的投入
解决方案
推荐阅读
- c++ - CStatusBar::GetStatusBarCtrl的SDK定义
- azure - 我可以在函数发布之前为 Azure 函数应用创建事件网格订阅吗?
- vb.net - 按 VB.NET 中的数字子类型对对象列表进行排序
- html - 如何仅使用内联 CSS(用于电子邮件)自定义无序列表项目符号?
- android - 有没有更好的方法在 android 中使用 rxjava 实现单一事实源
- controls - Elementor Widget - 中继器响应边距控制不起作用
- ios - 找不到“反应/RCTUtils.h”文件
- java - POI 和 XMLBeans 冲突
- python-3.x - 使用不同的线程显示图像时程序执行冻结
- bash - 如何在 bash 中获得更具可读性的 for 循环?