代码之家  ›  专栏  ›  技术社区  ›  Gamification

标识sqlacalchemy.exc.operationalerror

  •  7
  • Gamification  · 技术社区  · 7 年前

    我尝试捕获mysql/sqlachemy operationalerrors并替换拒绝访问的句柄(1045),这与拒绝连接(2003)不同。

    sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (1045, "Access denied for user … (Background on this error at: http://sqlalche.me/e/e3q8)
    sqlalchemy.exc.OperationalError: (pymysql.err.OperationalError) (2003, "Can't connect to MySQL server on 'localhost' ([Errno 111] Connection refused)") (Background on this error at: http://sqlalche.me/e/e3q8)
    

    我只是找不到任何关于如何用程序将这些区分开来的文档。我深入调查了资料来源,认为我可以检查err.orig.original_exception.errno的值,但事实并非如此。

    编辑:err.orig似乎没有为拒绝访问定义,这可能是一个错误。

    try:
      engine.scalar(select([1]))
    except sqlalchemy.exc.OperationalError as err:
      if err_______:
        print("Access Denied")
      elifif err_______:
        print("Connection Refused")
      else:
        raise
    

    这个问题真的让我恼火,甚至赏金也没有消息了。我开始相信这一定是sqlAlchemy中的一个bug,但是sqlAlchemy文档在这方面并不是很有描述性,而且我对sqlAlchemy和python是个新手,所以我很难判断。我也找不到IRC的支持,从这里我该去哪里?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Gamification    7 年前

    经过进一步的研究,我发现mysql的错误代码在 err.orig.args[0] . 所以答案是:

    try:
      engine.scalar(select([1]))
    except sqlalchemy.exc.OperationalError as err:
      if err.orig.args[0]==1045:
        print("Access Denied")
      elif err.orig.args[0]==2003:
        print("Connection Refused")
      else:
        raise
    
        2
  •  0
  •   Jab    7 年前

    尝试 err.args[0]

    try:
      engine.scalar(select([1]))
    except sqlalchemy.exc.OperationalError as err:
      if err.args[0] == 1045:
        print("Access Denied")
      elif err.args[0] == 2003:
        print("Connection Refused")
      else:
        raise
    

    这应该是你想要的。参考 documentation 更多阅读

    编辑

    看看API,比如 OperationalError 包裹 DBAPIError 那有一个 code 争论。很有可能只是替换 args[0] 具有 代码 在我的例子中。像这样:

    try:
      engine.scalar(select([1]))
    except sqlalchemy.exc.OperationalError as err:
      if err.code == 1045:
        print("Access Denied")
      elif err.code == 2003:
        print("Connection Refused")
      else:
        raise