python - 将 for 循环值传递给 API 调用字段
问题描述
我需要从 for 循环中获取多个值并将它们传递给 api 调用。我这样做的最佳方法是什么?
引用的值是“id”,我需要它们中的每一个来填充 api 调用中的 id 要求。
*** 我的 for 循环
response = json.loads(z)
for d in response:
for key, value in d['to'].items():
if key == 'id':
print(value)
*** API 调用
id = '' # str |
content_type = 'application/json' # str | (default to application/json)
accept = 'application/json' # str | (default to application/json)
fields = '' # str | Use a space seperated string of field parameters to include the data in the response. If omitted, the default list of fields will be returned. (optional) (default to )
filter = 'filter_example' # str | A filter to apply to the query. (optional)
x_org_id = '' # str | (optional) (default to )
api_response = api_instance.systemusers_get(id, content_type, accept, fields=fields, filter=filter, x_org_id=x_org_id)
解决方案
正如您自己指出的那样,您需要一个字符串。因此,当您遍历它们时,您必须将这些 id 添加到某个字符串中。所以让我们从创建一个空字符串开始。然后,当我们循环时,我们可以将它连接到字符串,而不是打印 ID
string = ""
for d in response:
for key, value in d['to'].items():
if key == 'id':
string += value
然后:
id = string
当然,现在我不知道该字符串对于该特定 API 需要采用什么格式。但是您应该能够使模式适应,例如,如果需要,用逗号分隔值。
(注意,我在这个问题的上下文中使用名称字符串来明确,但显然想出了一个更好的变量名称)
编辑:如何进行多个 API 调用
如果每次 API 调用只能发送一个 ID,那么您可以做两件事。也可以在循环中进行调用,或者将此 ID 保存到列表中。无论哪种情况,如果您将 API 调用包装到一个函数中,都会有所帮助:
def make_api_call(id)
id = id
content_type = 'application/json' # str | (default to application/json)
accept = 'application/json' # str | (default to application/json)
fields = '' # str | Use a space seperated string of field parameters to include the data in the response. If omitted, the default list of fields will be returned. (optional) (default to )
filter = 'filter_example' # str | A filter to apply to the query. (optional)
x_org_id = '' # str | (optional) (default to )
api_response = api_instance.systemusers_get(id, content_type, accept, fields=fields, filter=filter, x_org_id=x_org_id)
现在,您可以像这样在循环中调用它:
for d in response:
for key, value in d['to'].items():
if key == 'id':
make_api_call(value)
或者您可以构建一个列表,然后在该列表上运行调用:
all_ids = []
for d in response:
for key, value in d['to'].items():
if key == 'id':
all_ids.append(value)
for id in all_ids:
make_api_call(id)
(注意,我使用变量名 'id' 与问题相同。但是首选 '_id',因为 'id' 是内置的。)
推荐阅读
- java - 带有 Weblogic 12c 的 Eclipse 不会在断点处停止
- c# - 将实现接口的泛型类型类分配给作为接口的泛型类型
- visual-c++ - 对于 64 位目标,在 MSVC 2019 中找不到 MMX 内在函数,例如 _mm_cvtpd_pi32;从 2013 年开始变化?
- buffer - pyUSB - 延迟发送到设备?
- angular - 响应式表单提交状态
- javascript - 无法在 C# 中使用 Selenium WebDriver 执行 JavaScript 命令
- python - 为列表中的每个数据框添加一列时出现问题
- c++ - 初始化一个动态分配的数组
- python - 在分组数据中搜索信息并将其传播到组
- cortana - 用户单击调用 URL 的卡片后,如何在 Cortana 中继续旧对话?