python对Google搜索控制台API的批处理请求

2024-04-26 05:15:49 发布

您现在位置:Python中文网/ 问答频道 /正文

在过去的两天里,我一直试图用Python向Google搜索控制台API发送批处理请求,但我不确定文档以及如何继续。在

我不确定要遵循哪些文件。在

https://developers.google.com/api-client-library/python/guide/batch

https://developers.google.com/webmaster-tools/v3/how-tos/batch

第一份文件要求使用以下格式:

from apiclient.http import BatchHttpRequest

def insert_animal(request_id, response, exception):
  if exception is not None:
    # Do something with the exception
    pass
  else:
    # Do something with the response
    pass

service = build('farm', 'v2')

batch = service.new_batch_http_request(callback=insert_animal)

batch.add(service.animals().insert(name="sheep"))
batch.add(service.animals().insert(name="pig"))
batch.add(service.animals().insert(name="llama"))
batch.execute(http=http)

但是第二个帖子说要这样做:

^{pr2}$

但我不确定最后一个要我处理这个代码?在

另外,当尝试在请求包中发出Post请求时,我可以在哪里输入body参数?在

谢谢。在


Tags: 文件namehttpscomaddhttprequestservice
1条回答
网友
1楼 · 发布于 2024-04-26 05:15:49

这里有一种生成GET请求的技术,推测POST请求将非常类似。在本例中,我们向SearchAnalytics API发出批处理请求。在

#                  -#
# Define property and request payloads
#                  -#

web_property = 'https://example.com/'

request_body_1 = {
  "startDate": "2015-01-01",
  "endDate": "2016-01-01",
  "dimensions": ["country", "device"]
}
request_body_2 = {
  "startDate": "2016-01-01",
  "endDate": "2017-01-01",
  "dimensions": ["country", "device"]
}

#                #
# Make container to store results
#                #

class DataContainer:
    def __init__(self):
        self.data = []

    def callback(self, request_id, response, exception):
        if exception is not None:
            # do something ...
            pass
        else:
            print(request_id)
            self.data.append(response)

dc = DataContainer()

#                #
# Build and send batch requests
#                #

batch = service.new_batch_http_request(callback=dc.callback)

batch.add(service.query(siteUrl=web_property,
                        body=request_body_1))
batch.add(service.query(siteUrl=web_property,
                        body=request_body_2))

batch.execute()
print(dc.data)

相关问题 更多 >