我使用 React 的 fetch api 从 Flask 调用端点。我不断收到 psycopg2.ProgrammingError: 连接无法递归重新输入
I 端点调用位于循环内。
@app.get("/api/plot-project/<int:plot_id>/<int:project_id>")
def check_and_deactivate(plot_id, project_id):
with connection:
with connection.cursor() as cursor:
cursor.execute(PLOT_PROJECT_CHECK, (plot_id, project_id))
data = cursor.fetchall()
if len(data) == 0:
return "No data found", 404
removed = data.pop(0)
if len(data) > 1:
for row in data:
print(row[0])
cursor.execute(PLOT_PROJECT_DEACTIVATE, ('deleted', row[0], plot_id, project_id))
return { "Remain": removed }, 200
反应功能
const handleGet = () => {
data.forEach (async (item) => {
await getData(item.plotID, item.projectID);
})
}
获取句柄
const getData = async (plotID, projectID) => {
fetch(`http://127.0.0.1:5000/api/plot-project/${plotID}/${projectID}`, { method : 'GET', mode: 'no-cors', headers : { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }})
.then(data => data.json())
.then((response) => {
console.log('mapping', plotID, "to", projectID)
console.log('request succeeded with JSON response', response)
}).catch(function (error) {
console.log('mapping', plotID, "to", projectID)
console.log('no mapping yet')
});
}
当您尝试调用同一连接的上下文管理器(该连接已在上下文管理器中调用)时,会发生此错误。
要解决该问题,您有几种选择:
try:
result = None
with connection.cursor() as cursor:
cursor.execute(PLOT_PROJECT_CHECK, (plot_id, project_id))
data = cursor.fetchall()
if len(data) == 0:
result = "No data found", 404
removed = data.pop(0)
if len(data) > 1:
for row in data:
print(row[0])
cursor.execute(PLOT_PROJECT_DEACTIVATE, ('deleted', row[0], plot_id, project_id))
result = { "Remain": removed }, 200
conn.commit()
return result
except Exception as e:
logging.error(f"An error occurred: {str(e)}")
conn.rollback()
return "Database error", 500
connection.autocommit = True (you can place that code where you are making the connection)
with connection.cursor() as cursor:
cursor.execute(PLOT_PROJECT_CHECK, (plot_id, project_id))
data = cursor.fetchall()
if len(data) == 0:
return "No data found", 404
removed = data.pop(0)
if len(data) > 1:
for row in data:
print(row[0])
cursor.execute(PLOT_PROJECT_DEACTIVATE, ('deleted', row[0], plot_id, project_id))
return { "Remain": removed }, 200