【问题标题】:Flask API facing InterfaceError with PostgreSQLFlask API 面对 PostgreSQL 的 InterfaceError
【发布时间】:2019-07-15 13:17:07
【问题描述】:

我有一个基于 Flask RestPlus 扩展的 Flask API,并托管在 Google App Engine 上。该 API 执行从 Google Cloud SQL PostgreSQL 获取数据的基本工作。 API 工作正常,但有时它开始返回 InterfaceError: cursor already closed

奇怪的是,当我执行gcloud app deploy 时,API 又开始正常工作了。

这是 API 的基本格式:

import simplejson as json
import psycopg2

from flask import Flask, jsonify
from flask_restplus import Api, Resource, fields
from psycopg2.extras import RealDictCursor

app = Flask(__name__)
app.config['SWAGGER_UI_JSONEDITOR'] = True
api = Api(app=app,
          doc='/docs',
          version="1.0",
          title="Title",
          description="description")

app.config['SWAGGER_UI_JSONEDITOR'] = True
ns_pricing = api.namespace('cropPricing')

db_user = "xxxx"
db_pass = "xxxx"
db_name = "xxxxx"
cloud_sql_connection_name = "xxxxxx"

conn = psycopg2.connect(user=db_user,
                        password=db_pass,
                        host='xxxxx',
                        dbname=db_name)


@ns_pricing.route('/list')
class States(Resource):
    def get(self):
        """
        list all the states for which data is available

        """
        cur = conn.cursor(cursor_factory=RealDictCursor)
        query = """
                SELECT
                    DISTINCT state
                FROM
                    db.table
                """
        conn.commit()
        cur.execute(query)
        states = json.loads(json.dumps(cur.fetchall()))
        if len(states) == 0:
            return jsonify(data=[],
                           status="Error",
                           message="Requested data not found")
        else:

            return jsonify(status="Success",
                           message="Successfully retreived states",
                           data=states)

我应该如何解决才能不再看到错误?

【问题讨论】:

标签: python postgresql google-app-engine flask psycopg2


【解决方案1】:

最好使用诸如 SQLAlchemy / Flask-SQLAlchemy 之类的 ORM 来处理建立/重新建立连接部分。

不过,如果使用 psycopg2。您可以使用 try except 来捕获异常并重新建立连接。

try:
    cur.execute(query)
except psycopg2.InterfaceError as err:
    print err.message
    conn = psycopg2.connect(....)
    cur = conn.cursor()
    cur.execute(query)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 2013-04-03
    • 2021-09-04
    • 2017-12-02
    相关资源
    最近更新 更多