michaelliao / awesome-python3-webapp

小白的Python入门教程实战篇:网站+iOS App源码→ http://t.cn/R2PDyWN 赞助→ http://t.cn/R5bhVpf
GNU General Public License v3.0
2.37k stars 2.81k forks source link

orm.py 模块excute函数里面affected变量可能存在referenced before assignment. #46

Open ehds opened 6 years ago

ehds commented 6 years ago
async def execute(sql, args, autocommit = True):

   ....
    async with __pool.get() as conn:
       ...
        try:
            async with conn.cursor(aiomysql.DictCursor) as cur:
                await cur.execute(sql.replace('?','%s'),args)
                affected = cur.rowcount
                 ....
        except BaseException:
              .....
        return affected

在这个代码里面 cur.execute(sql.replace('?','%s'),args) 如果执行错误的话(例如重复插入unique key相同的数据),下面的local variable affected 变量不会被申明且赋值,而在try外面 affected 又被返回,此时会报错,且在调用excute函数的外面并没有捕获异常导致程序崩溃.

amchii commented 5 years ago

首先,如果对unique key插入相同数值的话会报MySQL内部错误IntegrityError(1062, "Duplicate entry 'test2' for key 'idx_email'")。然后这个return affect并不在try...中,也不在finally..中,所以怎么会返回呢?

cainianxi commented 5 years ago

可能会抛出异常,执行except下面的代码,执行完毕后返回affect。

amchii commented 5 years ago

return语句不在except中,执行完except后无finally则直接退出,怎么会return呢?难道你的报错信息中有到这一句吗?