• 记一个奇怪的python异常处理过程


    我的一个程序, 总是在退出时报异常, Exception TypeError: "'NoneType' object is not callable" in <function <lambda> at 0x016207F0> ignored. 这个异常用try except捕获不到. 不断测试来定位异常的引入点, 最后发现一旦引用了数据库模块

    mydatabase, 就会报错. 但直接运行该数据库模块, 没有异常.太诡异了!

    mydatabase模块, 代码很简单, 根据ini的设置, 初始化 sqlalchemy engine和 connection.

    在stackoverflow 也有人就shelve模块, 问了类似问题,   http://stackoverflow.com/questions/2180946/really-weird-issue-with-shelve-python

    根据 Alex Martelli 大牛的提示, 我在python后加了-v , 发现时在 mydatabase模块cleanup时, 抛出了异常, 难怪无法catch住.

    后来, 又搜出一个帖子, limodou 大牛发现sqlalchemy0.6.7 有类似的问题, http://comments.gmane.org/gmane.comp.python.sqlalchemy.user/31801, 官方的答复是, sqlalchemy 的 weakref cleanup 有bug. 我用的是SQLAlchemy-0.7.4, 说明这个版本也有问题. 看讨论, 0.7.7以上是没有这样的问题了. 

    主程序module, main.py

    #coding=utf-8

    '''

    module main.py

    '''

    from  fron.models import mydatabase

    pass

    数据库模块, mydatabase.py

    #coding=utf-8

    '''

    module mydatabase.py

    '''

    from sqlalchemy import engine_from_config,create_engine

    from sqlalchemy.schema import MetaData

    import logging

    from fron.fron_helper import fron_logging

    from fron.fron_helper import fron_config

    logger=logging.getLogger(__name__)

    fron_logging.configureLogger(logger)

    #set default db configuration if it did not been configured.

    if fron_config.db_configuration is None:

        fron_config.refreshConfig(dbBusyApplication=False)

    db = engine_from_config(fron_config.db_configuration,prefix='sqlalchemy.')

    metadata = MetaData(bind=db)

    #if transaction need, use connection to create trans object

    connection = db.connect()

    if __name__=="__main__":

        print('hello mydatabase')

    我又不想升级sqlalchemy, 根据 weakref cleanup 有问题这个提示, 大致判断应该是, db或 connection或metadata对象弱引用的问题, 逐一排除, 定位到关键是connection. 

    用如下两个函数, 代替原来的connection = db.connect() 代码行. 另外, 程序退出前, 要确保调用closeConnection()方法释放connection. 

    注意,我的程序是单线程,所以有一个全局connection,多线程会有问题的。

    connection=None

    def closeConnection():

        global connection

        if (connection is not None) and (connection.closed==False) :

            connection.close()

            logger.debug("disconnect database.")

            connection=None

    def getConnection():

        global connection

        if connection is None:

            connection=db.connect()

            logger.debug('To get database connection: %s',(connection,))

        return connection

  • 相关阅读:
    部署的influxdb没有可以web操作sql的页面
    JUnit5 @TestMethodOrder注释不起作用
    RestAssured 接口测试框架-环境搭建遇到的问题(1)
    PC前端代码 本地启动
    可有可无的“冒烟测试”
    adb devices 找不到连接设备 显示 List of devices attached 解决方法
    【转载】接口测试 rest-assured 使用指南(中文)
    工厂模式
    【腾讯云服务器】基于centos7搭建ftp服务器(vsftpd)
    centos下Django+uwsgi+nginx
  • 原文地址:https://www.cnblogs.com/harrychinese/p/one_python_cleanup_exception.html
Copyright © 2020-2023  润新知