在 Web 应用程序中使用 Postgres:“事务中止”错误

2024-02-16

最近,出于性能原因,我将正在开发的 Web 应用程序从 MySQL 迁移到 PostgreSQL(我需要 PostGIS 提供的功能)。现在经常会遇到如下错误:

current transaction is aborted, commands ignored until end of transaction block

服务器应用程序使用mod_python。该错误发生在呼叫功能中(即为该特定客户端创建新会话的功能)。下面是适当的代码段(异常发生在调用 sessionAppId 的行上:

def hello(req):
req.content_type = "text/json"
req.headers_out.add('Cache-Control', "no-store, no-cache, must-revalidate")
req.headers_out.add('Pragma', "no-cache")
req.headers_out.add('Expires', "-1")
instance = req.hostname.split(".")[0]

cookieSecret = '....' # whatever :-)
receivedCookies = Cookie.get_cookies(req, Cookie.SignedCookie, secret = cookieSecret)
sessionList = receivedCookies.get('sessions', None)
sessionId = str(uuid.uuid4())
if sessionList:
    if type(sessionList) is not Cookie.SignedCookie:
        return "{status: 'error', errno:1, errmsg:'Permission denied.'}"
    else:
        sessionList = sessionList.value.split(",")
        for x in sessionList[:]:
            revisionCookie = receivedCookies.get('rev_' + str(sessionAppId(x, instance)), None)
            # more processing here....
# .....
cursors[instance].execute("lock revision, app, timeout IN SHARE MODE")
cursors[instance].execute("insert into app (type, active, active_revision, contents, z) values ('session', true, %s, %s, 0) returning id", (cRevision, sessionId))
sAppId = cursors[instance].fetchone()[0]
cursors[instance].execute("insert into revision (app_id, type) values (%s, 'active')", (sAppId,))
cursors[instance].execute("insert into timeout (app_id, last_seen) values (%s, now())", (sAppId,))
connections[instance].commit()
# .....

这是 sessionAppId 本身:

def sessionAppId(sessionId, instance):
cursors[instance].execute("select id from app where type='session' and contents = %s", (sessionId, ))
row = cursors[instance].fetchone()
if row == None:
    return 0
else:
    return row[0]

一些澄清和附加问题:

  1. cursors[instance] 和connections[instance] 是数据库连接和在此域名上提供的Web 应用程序实例的光标。 IE。同一服务器为 example1.com 和 example2.com 提供服务,并使用这些字典根据请求所针对的服务器名称来调用相应的数据库。
  2. 我真的需要锁定 hello() 函数中的表吗?
  3. hello() 中的大部分代码都需要为每个浏览器选项卡维护一个单独的会话。我找不到仅使用 cookie 的方法,因为打开网站的浏览器选项卡共享 cookie 池。有更好的方法吗?

该错误是由先前的错误引起的。看一下这段代码:

>>> import psycopg2
>>> conn = psycopg2.connect('')
>>> cur = conn.cursor()
>>> cur.execute('select current _date')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
psycopg2.ProgrammingError: syntax error at or near "_date"
LINE 1: select current _date
                       ^

>>> cur.execute('select current_date')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
psycopg2.InternalError: current transaction is aborted, commands ignored until end of transaction block

>>> conn.rollback()
>>> cur.execute('select current_date')
>>> cur.fetchall()
[(datetime.date(2010, 2, 5),)]
>>> 

如果您熟悉扭曲,请查看twisted.enterprise.adbapi有关如何处理游标的示例。基本上你应该总是提交或回滚你的游标:

try:
    cur.execute("...")
    cur.fetchall()
    cur.close()
    connection.commit()
except:
    connection.rollback()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Web 应用程序中使用 Postgres:“事务中止”错误 的相关文章

  • 在 Python 3.6 中,为什么负数的分数次方在 numpy 数组中返回 nan?

    我最近开始学习Python 并且经历了NumPy 官方快速入门指南 https docs scipy org doc numpy dev user quickstart html indexing slicing and iterating
  • 从终端调用时 uvicorn 不工作

    我尝试通过 pip3 在系统上安装 uvicorn 这有效 但是我无法从命令行运行相同的命令 有关如何解决此问题的任何指示 Requirement already satisfied uvicorn in home vhawk19 loca
  • 出现导入错误:无法从“随机”导入名称“随机”[重复]

    这个问题在这里已经有答案了 我在我的计算机上多次运行我的代码 但没有出现此错误 但突然间这个来了 File e Python 3 8 0 lib site packages comtypes client code cache py lin
  • cv2.face.mindistancepredictcollector() 错误

    我已经安装了带有额外模块的 opencv 3 1 0 但是当我尝试使用 gt gt gt s cv2 face MinDistancePredictCollector 它返回一个错误 Traceback most recent call l
  • Python中使用cv2获取当前视频播放位置

    我正在尝试使用 CV2 和 Python 从播放视频中获取当前播放时间位置 如果可能 以毫秒为单位 目前我正在使用此示例代码来播放视频文件 import cv2 import numpy as np file name 2 mp4 wind
  • Python - 包和设置文件

    我有一个 python 包 需要从我的项目目录中提取设置 这是我的项目当前的结构 Project bin mypackage package files Project myproject project files start py se
  • 如何更改条形图上的 y 轴限制?

    我有一个df 我从中索引了europe n我绘制了一个条形图 europe n r 5 c 45 looks like this df Country string df Population numeric 变量 plt bar df C
  • WTForms 中的小数字段舍入

    我有一个包含价格小数字段的表单 如下所示 from flask ext wtf import Form import wtforms from wtforms validators import DataRequired from deci
  • Python MySQL 模块

    我正在开发一个需要与 MySQL 数据库交互的 Web 应用程序 但我似乎找不到任何真正适合 Python 的模块 我特别寻找快速模块 能够处理数十万个连接 和查询 所有这些都在短时间内完成 而不会对速度产生重大影响 我想我的答案将是游戏领
  • 更改Python pylab玫瑰/极坐标图中图例标题的字体大小

    我正在尝试更改玫瑰图或 极地 图上现有图例标题的字体大小 大部分代码是由不在的其他人编写的 我已经添加 ax legend title legend title setp l get title fontsize 8 添加标题 legend
  • ValueError:在 R 中使用 keras 模型时在用户代码中

    我正在尝试使用 R 在 R 中运行一维 CNNkeras包裹 我正在使用以下代码 library MASS library keras Create some data data Boston data lt Boston create a
  • 按字段名称对命名元组列表进行排序的 Pythonic 方法

    我想对命名元组列表进行排序 而不必记住字段名的索引 我的解决方案看起来相当尴尬 希望有人能有一个更优雅的解决方案 from operator import itemgetter from collections import namedtu
  • Cython:为什么 size_t 比 int 快?

    更改某些 Cython 变量的类型int输入size t可以显着减少某些功能的时间 30 但我不明白为什么 例如 cimport numpy as cnp import numpy as np def sum int cnp int64 t
  • 在 Docker 容器内运行时,如何自动在 API 路由文件中进行 FASTAPI 拾取更改?

    我通过 docker 运行 FastApi 在 docker compose 中创建一个名为 ingestion data 的服务 我的 Dockerfile FROM tiangolo uvicorn gunicorn fastapi p
  • 尝试修复我的功能

    我正在开发一个函数 我必须返回一个元组 其中第一个参数是最大数字的 str 第二个参数是 int 列表 这是示例以及我为该函数编写的内容 投票 G G N G C G 1 3 0 1 您必须将最大值的位置映射到正确的一方 parties N
  • 如何替换被测模块的文件访问引用

    pyfakefs https code google com p pyfakefs 听起来非常有用 它 最初是作为核心 Python 模块的一个适度的假实现来开发的 以支持中等复杂的文件系统交互 并于 2006 年 9 月在 Google
  • 在Python中引用不带换行符的长字符串

    我正在尝试在 Python 中编写一个长字符串 该字符串显示为 OptParser 选项的帮助项 在我的源代码 py 文件中 我想放置换行符 以便我的代码不会花费新行 但是 我不希望这些换行符影响代码运行时该字符串的显示方式 例如 我想写
  • python 函数返回 javascript date.getTime()

    我正在尝试创建一个简单的 python 函数 它将返回与 javascript 相同的值new Date getTime 方法 如所写here http www w3schools com js js dates asp javascrip
  • Python列表问题

    我在使用 python 列表时遇到问题 简化版本是 mylist1 some items in a list mylist2 mylist1 mylist1 pop i mylist insert i item print mylist1
  • Tensorflow ctc_loss_calculator:找不到有效路径

    当运行我的神经网络 双向 LSTM 进行音频识别时 我使用连接主义时间分类 CTC 但在某些时候 训练网络时我几乎每批都会收到来自 Tensorflow 的警告 W tensorflow core util ctc ctc loss cal

随机推荐