cx_oracle flask+apache+ 上的持久连接mod_wsgi

cx_oracle persistent connection on flask+apache+mod_wsgi

我已经在 apache+mod_wsgi

上部署了我的 Flask 应用程序

我正在使用 WSGI 守护进程模式并在 apache 中进行此配置 httpd.conf:

WSGIDaemonProcess flask_test user=apache group=apache threads=20

为简单起见,假设对于每个请求,我需要执行一个查询以将数据插入 Oracle 数据库。

所以在我的烧瓶应用程序中,我做了这样的事情:

# DB.py

import cx_Oracle
class DB:
    def __init__(self, connection_string):
        self.conn = cx_Oracle.connect(connection_string, threaded=True)
    
    def insert(query):
        cur = self.conn.cursor()
        cur.execute(query)
        cur.close()
        self.conn.commit()
# flask_app.py

from flask import Flask, request, jsonify
from DB import DB

app = Flask(__name__)
db = DB(connection_string)

@app.route("/foo", methods=["POST"])
def foo():
    post_data = request.get_json()
    
    # parse above data
    # create insert query with parsed data values
    
    db.insert(insert_processed_data_QUERY)

    # generate response
    
    return jsonify(response)

当我启动 apache+mod_wsgi 服务器时,创建了 DB 对象并建立了 DB 连接。 对于所有传入请求,使用相同的 DB 对象执行插入查询。

到目前为止这对我来说效果很好。但是我担心的是,如果长时间没有请求,数据库连接可能会超时,然后我的应用程序将无法处理新请求。

我一直在监视我的应用程序,发现数据库连接持续数小时。但是我很确定如果2-3天没有请求它可能会超时(?)

确保数据库连接永远保持打开状态的正确方法是什么? (即只要 apache 服务器是 运行)

使用池而不是独立连接。当您从池中获取连接时,它将检查连接是否不再有效并自动分配一个新连接。所以你需要这样的东西:

pool = cx_Oracle.SessionPool(user=user, password=password, dsn=dsn, min=1,
                             max=2, increment=1)

然后在您的代码中您需要执行以下操作:

with pool.acquire() as connection:
    # do what you need to do with the connection