Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法使用Python循环浏览分页API响应_Python_Json_Python 2.7_Loops_Hubspot - Fatal编程技术网

无法使用Python循环浏览分页API响应

无法使用Python循环浏览分页API响应,python,json,python-2.7,loops,hubspot,Python,Json,Python 2.7,Loops,Hubspot,所以,我用这个来抓我的头。使用HubSpot的API,我需要获得客户“门户”(帐户)中所有公司的列表。遗憾的是,标准API调用一次只能返回100家公司。当它返回一个响应时,它包含两个参数,使通过响应进行分页成为可能 其中一个是“has more”:True(这让您知道是否可以期待更多页面),另一个是“offset”:12345678(用于偏移请求的时间戳) 这两个参数可以传递回下一个API调用以获取下一页。例如,初始API调用可能如下所示: "https://api.hubapi.com/com

所以,我用这个来抓我的头。使用HubSpot的API,我需要获得客户“门户”(帐户)中所有公司的列表。遗憾的是,标准API调用一次只能返回100家公司。当它返回一个响应时,它包含两个参数,使通过响应进行分页成为可能

其中一个是
“has more”:True
(这让您知道是否可以期待更多页面),另一个是
“offset”:12345678
(用于偏移请求的时间戳)

这两个参数可以传递回下一个API调用以获取下一页。例如,初始API调用可能如下所示:

"https://api.hubapi.com/companies/v2/companies/?hapikey={hapikey}".format(hapikey=wta_hubspot_api_key)
"https://api.hubapi.com/companies/v2/companies/?hapikey={hapikey}&offset={offset}".format(hapikey=wta_hubspot_api_key, offset=offset)
而跟进电话可能看起来像:

"https://api.hubapi.com/companies/v2/companies/?hapikey={hapikey}".format(hapikey=wta_hubspot_api_key)
"https://api.hubapi.com/companies/v2/companies/?hapikey={hapikey}&offset={offset}".format(hapikey=wta_hubspot_api_key, offset=offset)
这就是我到目前为止所尝试的:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sys
import os.path
import requests
import json
import csv
import glob2
import shutil
import time
import time as howLong
from time import sleep
from time import gmtime, strftime

HubSpot_Customer_Portal_ID = "XXXXXX"

wta_hubspot_api_key = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"

findCSV = glob2.glob('*contact*.csv')

theDate = time=strftime("%Y-%m-%d", gmtime())
theTime = time=strftime("%H:%M:%S", gmtime())

try:
    testData = findCSV[0]
except IndexError:
    print ("\nSyncronisation attempted on {date} at {time}: There are no \"contact\" CSVs, please upload one and try again.\n").format(date=theDate, time=theTime)
    print("====================================================================================================================\n")
    sys.exit()

for theCSV in findCSV:

    def get_companies():
        create_get_recent_companies_call = "https://api.hubapi.com/companies/v2/companies/?hapikey={hapikey}".format(hapikey=wta_hubspot_api_key)
        headers = {'content-type': 'application/json'}
        create_get_recent_companies_response = requests.get(create_get_recent_companies_call, headers=headers)
        if create_get_recent_companies_response.status_code == 200:

            offset = create_get_recent_companies_response.json()[u'offset']
            hasMore = create_get_recent_companies_response.json()[u'has-more']

            while hasMore == True:
                for i in create_get_recent_companies_response.json()[u'companies']:
                    get_more_companies_call = "https://api.hubapi.com/companies/v2/companies/?hapikey={hapikey}&offset={offset}".format(hapikey=wta_hubspot_api_key, offset=offset)
                    get_more_companies_call_response = requests.get(get_more_companies_call, headers=headers)
                    companyName = i[u'properties'][u'name'][u'value']
                    print("{companyName}".format(companyName=companyName))


        else:
            print("Something went wrong, check the supplied field values.\n")
            print(json.dumps(create_get_recent_companies_response.json(), sort_keys=True, indent=4))

    if __name__ == "__main__":
        get_companies()
        sys.exit()
问题是,它只是不断返回相同的初始100个结果;发生这种情况是因为参数
“has more”:True
在初始调用时为True,因此它将继续返回相同的值

我的理想情况是,我能够在大约120个响应页面上解析所有公司(大约有12000家公司)。当我浏览每个页面时,我想将它的JSON内容附加到一个列表中,这样最终我就有了这个列表,其中包含所有120个页面的JSON响应,这样我就可以解析该列表,以便在不同的函数中使用

我迫切需要一个解决方案:(

这是我在主脚本中替换的函数:

            def get_companies():

                create_get_recent_companies_call = "https://api.hubapi.com/companies/v2/companies/recent/modified?hapikey={hapikey}".format(hapikey=wta_hubspot_api_key)
                headers = {'content-type': 'application/json'}
                create_get_recent_companies_response = requests.get(create_get_recent_companies_call, headers=headers)
                if create_get_recent_companies_response.status_code == 200:

                    for i in create_get_recent_companies_response.json()[u'results']:
                        company_name = i[u'properties'][u'name'][u'value']
                        #print(company_name)
                        if row[0].lower() == str(company_name).lower():
                            contact_company_id = i[u'companyId']
                            #print(contact_company_id)
                            return contact_company_id
                else:
                    print("Something went wrong, check the supplied field values.\n")
                    #print(json.dumps(create_get_recent_companies_response.json(), sort_keys=True, indent=4))

问题似乎是:

  • 您在第一次通话中获得了偏移量,但不必处理此通话返回的实际公司数据
  • 然后,您在while循环中使用相同的偏移量;您从不使用后续调用中的新偏移量。这就是为什么每次都使用相同的公司
我认为这段针对
get_companys()
的代码应该适合您。显然,我无法测试它,但希望它可以:

def get_companies():
        create_get_recent_companies_call = "https://api.hubapi.com/companies/v2/companies/?hapikey={hapikey}".format(hapikey=wta_hubspot_api_key)
        headers = {'content-type': 'application/json'}
        create_get_recent_companies_response = requests.get(create_get_recent_companies_call, headers=headers)
        if create_get_recent_companies_response.status_code == 200:

            while True:
                for i in create_get_recent_companies_response.json()[u'companies']:
                    companyName = i[u'properties'][u'name'][u'value']
                    print("{companyName}".format(companyName=companyName))
                offset = create_get_recent_companies_response.json()[u'offset']
                hasMore = create_get_recent_companies_response.json()[u'has-more']
                if not hasMore:
                    break
                else:
                    create_get_recent_companies_call = "https://api.hubapi.com/companies/v2/companies/?hapikey={hapikey}&offset={offset}".format(hapikey=wta_hubspot_api_key, offset=offset)
                    create_get_recent_companies_response = requests.get(create_get_recent_companies_call, headers=headers)


        else:
            print("Something went wrong, check the supplied field values.\n")
            print(json.dumps(create_get_recent_companies_response.json(), sort_keys=True, indent=4))
严格来说,
中断后的
else
不是必需的,但它符合“显式优于隐式”的原则


请注意,您只需检查一次200响应代码,如果循环中出现错误,您将错过它。您可能应该将所有调用放入循环中,每次都检查是否有正确的响应。

Hi@SiHa,感谢您的响应-不幸的是,这也返回了相同的结果,尽管返回了前100个连续值不是一个接一个地离开(这是一个进步!)@Marko抱歉,我错过了你使用不同名称的事实(
create\u get\u recent\u companys…
vs
get\u more\u companys\u call
)在while循环的内部和外部。这意味着,在我的第一稿中,虽然循环中获取了更多的结果,但每次都会重复第一个响应。我现在已经更改了名称,使它们相同。希望它现在可以工作。@SiHia你是一个绝对的传奇-完全工作了。我还有一个问题。Th上面的脚本是一个“测试脚本”-我试图缩小主脚本的功能范围。但是,回到主脚本中,我需要替换的功能是我现在在上面添加的功能…您认为收集每页结果的最佳方式是什么?我将尝试将其附加到列表中,或者您认为我可以“返回”吗正如上面最初所做的那样?要详细说明-
get_companys()
函数实际上位于另一个函数中,该函数在CSV中的每一行都会运行。我想理想情况下,我最好使用测试脚本将所有公司下拉到本地文件中,然后使用该脚本为所有其他操作提取公司ID,这将比提取所有120页文件快得多我同意,将所有数据向下拉一次,然后在本地处理可能会更快。从
get_companys()
返回的结构在很大程度上取决于所需的数据;如果只是名称,则可以使用一个简单的列表,但如果还需要关联数据,则可能需要一个字典(或者可能只是原始的JSON)最好。你现在有你需要继续的东西。如果你再次陷入困境,最好再发布另一个问题。祝你编码愉快!