我在 Tornado 中有这个 python 代码:
if not usr:
self.lock_tables("write", ['devices_permissions'])
self.db.execute("INSERT devices_permissions SET user_id=%s, network_id=%s, device_id=%s, perm=%s",
usrid, netid, sensid, perm)
self.unlock_tables();
else:
if perm == 0:
self.lock_tables("write", ['devices_permissions'])
self.db.execute("DELETE FROM devices_permissions \
WHERE user_id=%s AND device_id=%s", usrid, sensid)
self.unlock_tables();
else:
self.lock_tables("write", ['devices_permissions'])
self.db.execute("UPDATE devices_permissions SET perm=%s \
WHERE user_id=%s AND device_id=%s", perm, usrid, sensid)
self.unlock_tables();
我对第二个if...else语句有疑问。我的程序进入第一个 else 块,但在第二个if...else似乎无法使用if perm == 0语句。我已经打印了perm变量,它的值为 0。所以我不知道错误在哪里。
我想要这个if...else语句,因为我想从我的数据库中删除不再拥有设备权限的用户。
perm是值为 0 或 1 的变量。usr是用户列表。非常感谢你。
编辑
我以这种方式更改语句:
# Check whether the user has already priviledges on the device
self.lock_tables("read", ['devices_permissions'])
usr = self.db.get("SELECT device_id, user_id FROM devices_permissions \
WHERE user_id=%s AND device_id=%s", usrid, sensid)
self.unlock_tables();
if not usr:
self.lock_tables("write", ['devices_permissions'])
self.db.execute("INSERT devices_permissions SET user_id=%s, network_id=%s, device_id=%s, perm=%s",
usrid, netid, sensid, perm)
self.unlock_tables();
elif perm == 0:
self.lock_tables("write", ['devices_permissions'])
self.db.execute("DELETE FROM devices_permissions \
WHERE user_id=%s AND device_id=%s", usrid, sensid)
self.unlock_tables();
else:
self.lock_tables("write", ['devices_permissions'])
self.db.execute("UPDATE devices_permissions SET perm=%s \
WHERE user_id=%s AND device_id=%s", perm, usrid, sensid)
self.unlock_tables();
经过一些测试,我认为程序总是在 if not usr 语句中输入,如果 usr 列表不为空。有什么问题?