Flask API在PostgreSQL中面临InterfaceError

时间:2019-07-15 13:17:07

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

我有一个基于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)

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

1 个答案:

答案 0 :(得分:0)

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

但是,如果使用psycopg2。您可以使用try除外来捕获异常并重新建立连接。

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