一段bug

本文探讨了Python中处理数据库缓存时遇到的问题,特别是针对字段值为0时的误判,提出了有效的解决方案,并总结了关于数据库ID字段设计的经验教训。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    def __load_table_to_cache(self):
        mysql = self.get_conn()
        cur = mysql.cursor()

        cur.execute('select clip, item, title, section, channel from general_video')
        for line in cur.fetchall():
            self.c_video[line[0]] = line[1:]


        mysql.close()
        print "general_video table loaded to cache"


    def __update_clip(self, clip, item, title, section, channel):

        x = self.c_video[clip]
        if x:
            if x[2] and x[2] != 65535 and x[3] and x[3] >= 0 and x[3] <= 7:
                return False, x[2], x[3]

            if x[2] and x[2] != 65535 and section == 65535:
                section = x[2]

            if x[3] and x[3] >=0 and x[3] <= 7 and channel >= 8:
                channel = x[3]

        self.c_video[clip] = [item, title, section, channel]

        sqlstr = """insert into general_video(clip, item, title, section, channel)
                    values(%s, %s, '%s', %s, %s) 
                    on duplicate key update section = %s, channel = %s
                 """ %(clip, item, title, section, channel, section, channel)

        self.insert_sql(sqlstr)
        return True, section, channel

我的一段bug代码。self.c_video是一个字典,存放的是从数据库里取出的数据,作为缓存,其中,channel字段取0是合法的。但在_update_clip中,我原先期望用x[3]作为判断x[3]是否存在的,但实际是判断的x[3]的值。

        channel = self.__update_channel(p.get('channel'), item)
        if (not channel) or channel == 255:
            channel = self.r.hget('pink_item_channel_cms', item)
        if not channel:
            channel = 255

原本是判断如果channel为空,则对它重新赋值。但channel有时候可以取0,这是一个合法值。如果简单的进行not判断,则会导致channel=0的那些合法值被覆盖了。


结论:

1,对于python变量是否为空的判断,需要先留意该变量是否可以取0.如果是0,则会引起混淆。

2,对于数据库的ID字段,尽量不要是0作为ID

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值