You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中使用`in`无法在字典中找到session token问题排查

问题

我有一个Python脚本从MySQL数据库提取数据并转换为Python字典,尝试使用in关键字在字典中查找session token,但始终无法成功。我曾用自定义函数验证token与字典中存储的session字符串完全一致,但判断逻辑仍报错。相关代码、自定义函数、程序输出如下,需要在保留现有字典结构的前提下解决该问题:

自定义函数

def difference(string1, string2):
      # Split both strings into list items
  string1 = string1.split()
  string2 = string2.split()

  A = set(string1) # Store all string1 list items in set A
  B = set(string2) # Store all string2 list items in set B
 
  str_diff = A.symmetric_difference(B)
  isEmpty = (len(str_diff) == 0)
 
  if isEmpty:
    print("No Difference. Both Strings Are Same")
  else:
    print("The Difference Between Two Strings: ")
    print(str_diff)
  
  print('The programs runs successfully.')

核心代码片段

try:
            import Debug
            Debug.difference(token, USERS['danielcaminero@plairstudio.com']['session'])
            print(token)
            print(USERS['danielcaminero@plairstudio.com']['session'])
            print(USERS)
            # check if user exists
            if token not in USERS:
                print("Doesnt work :(")
                raise Exception('Invalid token')

        except:
            
            return {'message': 'Invalid token'}, 401

程序输出

No Difference. Both Strings Are Same
The programs runs successfully.
2681bd95970590adcd5950a3f7c90ef7
2681bd95970590adcd5950a3f7c90ef7
{'danielcaminero@plairstudio.com': {'password': '44b4cedfad79d8e47d1430b4da4198f72162dbc0d49452d8dc968546e1b48f14', 'role': '1', 'id': 1, 'session': '2681bd95970590adcd5950a3f7c90ef7'}}
Doesnt work :(
127.0.0.1 - - [09/Apr/2023 14:00:52] "GET /protected HTTP/1.1" 401 -

问题原因

token not in USERS的判断逻辑错误:in关键字作用于字典时,默认检查的是字典的顶层键,而你的USERS字典顶层键是邮箱地址,token实际存储在每个用户子字典的session字段中,所以这个判断永远会返回True,进而触发异常。

解决方法

在保留现有字典结构的前提下,提供两种可行方案:

方案1:遍历验证所有用户的session

直接遍历USERS的所有值,检查是否存在匹配的session token:

try:
    import Debug
    Debug.difference(token, USERS['danielcaminero@plairstudio.com']['session'])
    print(token)
    print(USERS['danielcaminero@plairstudio.com']['session'])
    print(USERS)
    
    # 修正判断逻辑:遍历所有用户的session字段
    token_valid = False
    for user_info in USERS.values():
        if user_info.get('session') == token:
            token_valid = True
            break
    if not token_valid:
        print("Doesnt work :(")
        raise Exception('Invalid token')

except:
    return {'message': 'Invalid token'}, 401

方案2:维护反向映射字典(提升查询效率)

如果用户数量较多,遍历的效率偏低,可以额外维护一个以token为键的反向字典,既保留原结构,又实现O(1)时间复杂度的查询:

# 从数据库加载USERS后,生成反向映射字典
session_map = {user_data['session']: email for email, user_data in USERS.items()}

try:
    import Debug
    Debug.difference(token, USERS['danielcaminero@plairstudio.com']['session'])
    print(token)
    print(USERS['danielcaminero@plairstudio.com']['session'])
    print(USERS)
    
    # 用反向字典快速验证token
    if token not in session_map:
        print("Doesnt work :(")
        raise Exception('Invalid token')

except:
    return {'message': 'Invalid token'}, 401

内容的提问来源于stack exchange,提问作者Caminero

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 01:05:31