【发布时间】: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)
我应该如何解决才能不再看到错误?
【问题讨论】:
-
这能回答你的问题吗? psycopg2 : cursor already closed
标签: python postgresql google-app-engine flask psycopg2