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