Flask服务器终止时如何清理?

时间:2019-04-22 05:21:30

标签: python python-3.x flask

我已经编写了Flask服务器(内部服务使用它来进行REST调用),而我的设置中没有apache / nginx / django

此烧瓶服务器在docker容器中运行,我有一个/ healthcheck端点,该端点从数据库中获取一些信息,并根据该信息返回200或错误代码。

最初,我使用psycopg2连接到Postgres数据库,并在此调用结束时断开连接

@app.route("/healthcheck", methods=['POST', 'GET'])
def healthcheck():
...
 try:
        postgres_conn = psycopg2.connect(host=name, database=db,
                                user=user, password=pass)
        cur = postgres_conn.cursor()
        cur.execute(
            "SELECT \"Value\" FROM mytable WHERE (\"Key\" = 'PARAMETERS')")
...
    except (Exception, psycopg2.DatabaseError) as error:
        app.logger.info('Error connecting to Postgres database', error)
        raise abort(500)
    finally:
        if postgres_conn:
            if cur:
                cur.close()
            postgres_conn.close()  

现在,我正在尝试使数据库连接在多个REST调用之间保持持久状态


app = Flask(__name__)

postgres_conn = None

@app.route("/healthcheck", methods=['POST', 'GET'])
def healthcheck():
...
    global postgres_conn

    try:
        if postgres_conn is None:
            postgres_conn = psycopg2.connect(host=name, database=db,
                                user=user, password=pass)
            cur = postgres_conn.cursor()
            cur.execute(
            "SELECT \"Value\" FROM mytable WHERE (\"Key\" = 'PARAMETERS')")
...
    except (Exception, psycopg2.DatabaseError) as error:
        app.logger.info('Error connecting to Postgres database', error)
        raise abort(500)

我无法关闭连接(cur.close()和 现在位于finally块中的postgres_conn.close())。我试图在Flask服务器正常关闭或重新启动之前弄清楚该怎么做。我发现了@ app.teardown_appcontext,但这发生在请求结束时,而不是在Flask服务器生命周期的尽头。

0 个答案:

没有答案
相关问题