【问题标题】:Getting error messages from psycopg2 exceptions从 psycopg2 异常中获取错误消息
【发布时间】:2014-08-11 11:47:13
【问题描述】:

这是我第一个广泛使用 psycopg2 的项目。我正在尝试找到一种方法来在连接尝试失败时提取 psql 错误消息。如果所有变量都设置正确,我已经测试过下面的代码将起作用,但是每当发生错误情况(例如用户选择不存在的数据库)时,Python 会给我以下信息:

I am unable to connect to the database
None
Traceback (most recent call last):
  File "./duplicate_finder.py", line 163, in <module>
    main(sys.argv[1:])
  File "./duplicate_finder.py", line 142, in main
    print e.diag.message_detail
AttributeError: 'OperationalError' object has no attribute 'diag'

是否有一个简单的、包罗万象的方法来捕获 psql 在连接失败时生成的任何错误消息,或者我是否需要为多个 psycopg2 异常编写 except 块?

从我的脚本中提取:

import sys, getopt, os, time, csv, psycopg2

    ...
    ...

    conn_string = "host=" + dbhost + " dbname=" + database + " user=" + dbuser + " password=" + dbpass
    try:
        conn = psycopg2.connect(conn_string)
    except psycopg2.Error as e:
        print "Unable to connect!"
        print e.pgerror
        print e.diag.message_detail
        sys.exit(1)
    else:
        print "Connected!"
        cur = conn.cursor()
        cur.execute("SELECT id, lastname, firstname, location FROM test ORDER BY ctl_upd_dttm DESC;")
        print cur.fetchone()
        ...
        conn.close()

【问题讨论】:

    标签: python postgresql psycopg2


    【解决方案1】:

    从 Python 3.9 开始(.removesuffix()f-strings)我使用

    except psycopg2.Error as e:
      log.error(f"{type(e).__module__.removesuffix('.errors')}:{type(e).__name__}: {str(e).rstrip()}")
      if conn: conn.rollback()
    

    其中loglogger

    连接错误直接存在于 psycopg2 模块中,而语法错误则存在于 psycopg2.errors 子模块中。每条 psycopg2 错误消息的末尾都有一个unwanted newline

    【讨论】:

      【解决方案2】:

      因为

      类'psycopg2.errors.InvalidCursorName'

      在 Django 上。如果是这种情况,请务必进行迁移

      【讨论】:

        【解决方案3】:

        当我尝试捕获异常时,对于连接错误,e.pgerror 始终为 None。下面的代码块通过直接打印'e'来解决这个问题。

        try:
            conn = psycopg2.connect(conn_string)
        except psycopg2.OperationalError as e:
            print('Unable to connect!\n{0}').format(e)
            sys.exit(1)
        else:
           print('Connected!')
           # do stuff
        

        例如密码认证失败的情况:

        Unable to connect!
        FATAL:  password authentication failed for user "user"
        

        我知道这个问题已经有一年了,但希望将来可以帮助某人

        【讨论】:

          【解决方案4】:

          您正在使用基类psycopg2.Error 捕获所有异常。您的问题可能是diag 属性是psycopg2 2.5 中的新属性。你的版本是什么?

          >>> print psycopg2.__version__
          2.5.1 (dt dec pq3 ext)
          

          【讨论】:

          • >>> import psycopg2 >>> print psycopg2.__version__ 2.0.14 (dt dec ext pq3) 看起来我落后了几个版本。不幸的是,根据我的发行版(Scientific Linux)repos + epel,这似乎是最新版本。可能必须使用 this 走源路线。 . .
          • 只是好奇,在我开始手动升级 psycopg2 的潜在危险任务之前,有没有办法在旧版本的 psycopg2 中获取 psql 连接错误消息,或者我只是坚持给他们一个出现问题时的通用消息?
          • @sirjames2004 我不知道。但是使用setuppip 安装非常简单:initd.org/psycopg/install。请记住先yum remove psycopg2
          • @sirjames2004 而你需要 Python 2.5+ 才能获得 psycopg 2.5
          猜你喜欢
          • 2011-05-26
          • 2017-02-11
          • 2012-10-08
          • 1970-01-01
          • 2015-04-19
          • 2012-05-08
          • 2014-06-14
          • 1970-01-01
          • 2019-02-22
          相关资源
          最近更新 更多