我正在尝试处理Freshservice v1 API,该API返回分页结果,但在最后一页中不包含EOF密钥。因此,我试图用结果构建一个字典,然后在到达最后一页时进行计算。
目前,我有以下代码:
assets = dict()
page = 1
request_string = 'https://domain.freshservice.com/cmdb/items.json?page=%s' % page
returned_assets = requests.get(request_string, auth=(user, pw)).json()
assets.update(returned_assets)
if len(returned_assets) == 50: # if there are 50 assets, there either more pages or this is a full page
while len(returned_assets) != 0:
page += 1
request_string = 'https://domain.freshservice.com/cmdb/items.json?page=%s' % page
returned_assets = requests.get(request_string, auth=(user, pw)).json()
assets.update(returned_assets)
当前,当我运行代码时,需要花费 age 来将assets
更新为returned_assets
。
这是API的示例响应:
[
{
"agent_id": null,
"asset_tag": "",
"assigned_on": null,
"ci_type_id": 6000806999,
"created_at": "2017-07-11T15:29:22+01:00",
"department_id": null,
"depreciation_id": null,
"description": "Test",
"display_id": 2,
"id": 6002201649,
"impact": 3,
"location_id": null,
"name": "Test entry",
"salvage": null,
"updated_at": "2018-07-05T17:39:20+01:00",
"usage_type": 1,
"user_id": null,
"department_name": null,
"used_by": null,
"business_impact": "High",
"agent_name": null,
"levelfield_values": {
"state_6000742951": "Operational",
"bandwidth_6000742951": "1Gbit/s",
"network_range_6000742951": null,
"carrier_6000806999": "Test",
"supplier_circuit_id_6000806999": "AAAAAAAAA",
"carrier_tail_provider_6000806999": "Test",
"carrier_tail_order_id_onea_6000806999": null,
"a_end_address_6000806999": "Test",
"a_end_termination_details_6000806999": null,
"b_end_address_6000806999": "Test",
"b_end_termination_details_6000806999": "Test",
"a_end_vlan_id_6000806999": 0,
"b_end_vlan_id_6000806999": "0",
"notes_6000806999": null
},
"ci_type_name": "Circuit",
"location_name": null,
"product_name": null,
"vendor_name": null,
"state_name": null
}
]
如何才能更有效地做到这一点?将结果存储在列表中会更好吗?
答案 0 :(得分:0)
根据各种海报的建议,我尝试将结果添加到列表中,并且处理时间大大加快了。我使用list.extend(new_list_to_add)
将新条目添加到列表中。
新代码如下:
assets = []
page = 1
request_string = 'https://domain.freshservice.com/cmdb/items.json?page=%s' % page
returned_assets = requests.get(request_string, auth=(user, pw)).json()
assets = returned_assets
if len(assets) == 50: # if there are 50 assets, there either more pages or this is a full page
while len(returned_assets) != 0:
page += 1
request_string = 'https://domain.freshservice.com/cmdb/items.json?page=%s' % page
returned_assets = requests.get(request_string, auth=(user, pw)).json()
assets.extend(returned_assets)