如何在Python中关联两个API数据,实现类似SQL表关联效果
解决思路与实现代码
1. 数据关联核心逻辑
类似SQL的表关联,我们可以把员工照片数据转换为以Id(对应员工详情的StaffId)为键、照片为值的字典,这样遍历员工详情时能快速匹配到对应照片,效率远高于嵌套循环查找。
2. 修改后端视图函数
合并两个API的调用逻辑,处理数据关联后传递给模板:
import requests import random from django.shortcuts import render def StaffCombined(request): # API地址 details_url = "https://test.com/api/Staff/GetStaffDetails" photos_url = "https://test.com/api/Staff/GetStaffPhotos" headers = { "X-DOMAIN": "test", "X-TOKEN": "123456789qwertyuiop", "User-Agent": "", } # 获取员工详情并随机筛选5条 details_response = requests.post(details_url, headers=headers) details_data = details_response.json() selected_staff = random.sample(details_data, min(5, len(details_data))) # 获取照片数据并构建映射字典 photos_response = requests.post(photos_url, headers=headers) photos_data = photos_response.json() photo_map = {photo["Id"]: photo["Photo"] for photo in photos_data} # 给每个员工匹配照片(无照片则留空) for staff in selected_staff: staff["Photo"] = photo_map.get(staff["StaffId"], "") return render(request, "StaffCombined.html", {"staff_data": selected_staff})
3. 编写合并后的HTML模板(StaffCombined.html)
在原有员工详情表格基础上添加照片列:
<table border="1"> <tr> <td>STAFFID</td> <td>FIRSTNAME</td> <td>LASTNAME</td> <td>EMAIL</td> <td>PHOTO</td> </tr> {% for staff in staff_data %} <tr> <td>{{ staff.StaffId }}</td> <td>{{ staff.Firstname }}</td> <td>{{ staff.Lastname }}</td> <td>{{ staff.Email }}</td> <td> {% if staff.Photo %} <img src="data:image/jpeg;base64,{{ staff.Photo }}" width="100px"> {% else %} <span>无照片</span> {% endif %} </td> </tr> {% endfor %} </table>
补充说明
- 上述逻辑相当于SQL的
LEFT JOIN,确保没有照片的员工也能正常展示;如果只需要有照片的员工,可在匹配后过滤掉无照片的条目。 - 字典映射的方式时间复杂度为O(n),比嵌套循环的O(n*m)效率更高,适合数据量较大的场景。
内容的提问来源于stack exchange,提问作者bickyz




