Python 如果只能获取完整的用户列表,则从REST GET读取单个用户条目

Python 如果只能获取完整的用户列表,则从REST GET读取单个用户条目,python,json,rest,search,Python,Json,Rest,Search,我使用的软件只允许我获取所有用户的信息,而我的项目要求我只获取一个特定用户。我只需要他的ID,我会通过他的电子邮件找到它(因为它是独一无二的) 该程序创建一个用户(通过POST)并将其数据(如电子邮件)存储在变量中,然后读取将分配给该用户的设备列表。为此,程序必须: 获取所有用户(我无法理解为什么软件作者不允许获取单个用户) 过滤用户,这样它就可以从您的示例中找到我新创建的用户,看起来您从端点获得了一个JSON响应。这很好,因为这个JSON可以解析为列表/字典 您的方法可以是这样的。从广义上讲,

我使用的软件只允许我获取所有用户的信息,而我的项目要求我只获取一个特定用户。我只需要他的ID,我会通过他的电子邮件找到它(因为它是独一无二的)

该程序创建一个用户(通过POST)并将其数据(如电子邮件)存储在变量中,然后读取将分配给该用户的设备列表。为此,程序必须:

  • 获取所有用户(我无法理解为什么软件作者不允许获取单个用户)

  • 过滤用户,这样它就可以从您的示例中找到我新创建的用户,看起来您从端点获得了一个JSON响应。这很好,因为这个JSON可以解析为列表/字典

    您的方法可以是这样的。从广义上讲,这是一种可能的战略:

  • 从用户端点获取所有用户
  • 将响应JSON解析为字典列表
  • 在所有用户上循环,在找到用户时中断循环
  • 使用在搜索中找到的用户ID执行某些操作

  • 嗯,好吧,我试试这个。
    inputText = self.imeiInput.GetValue().splitlines() # reads input and creates a list
    url = "https://example.com/api/users/"
    userList = requests.get(url, auth=(login, password)).content
    foundUser = re.findall(givenMail, str(userList)) # givenMail provided by function argument
    print(userList)
    print(foundUser) # prints only searched mail
    for imei in inputText:
        self.TrackerAssign(imei, foundUser) # do your stuff
    
    b'[{
        "id":1,
        "attributes": {
        ...
        },
        "name":"username",
        "login":"",
        "email":"test@example.com",
        "phone":"999999999",...
    },
    {
        "id":2,
        "attributes": {
        ...
        },
        "name":"username2",
        "login":"",
        "email":"test2@exmaple.com",
        "phone":"888888888",...
    },
    ...]'
    
    response = requests.get(url, auth=(login, password))  # receive a Response instance
    user_list = response.json()  # parse the body to a dictionary
    
    for user in user_list:
        # Compare the email of this user with the target, using get to catch users with no email specified.
        if user.get("email") == given_mail:
            desired_user = user
            break  # if we find the correct user, we exit the loop
    else:
        # If we never find the desired user, we raise an exception.
        raise ValueError("There is no user with email %s", given_email")
    
    print(f"The ID of the user I am looking for is {desired_user["id"]}.")