Google API批量请求会通过Python客户端为每次调用返回HttpError 404

时间:2017-07-26 13:21:42

标签: python youtube-api youtube-data-api google-api-python-client

我有一个基于google-api-python-client的小应用程序,但批处理请求已经工作了几天(错误404)。

例如,以下代码在几天前工作正常。

from apiclient.http import BatchHttpRequest
from apiclient.discovery import build
import json

DEVELOPER_KEY = "foobar"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"

channelIds = ['UC2C_jShtL725hvbm1arSV9w','UC2C_jShtL725hvbm1arSV9w']

parts_list = [
"id",
"brandingSettings",
]

fields_list = [
"items/id",
"items/brandingSettings/channel",    
]

parts = ",".join(parts_list)
fields = ",".join(fields_list)

request_map = {}

def this_is_the_callback_function(request_id, response, exception):
  if exception is not None:
    # Do something with the exception
    print exception
    pass
  else:
    print request_id
    print request_map[int(request_id)]
    print json.dumps(response,sort_keys=True, indent=4)

service = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)
batch = service.new_batch_http_request(callback=this_is_the_callback_function)

channels = service.channels()
i = 0
for c in channelIds:
    i += 1
    request_map[i] = c
    request = channels.list(id=c,part=parts, fields=fields)
    batch.add(request)
print request_map
batch.execute()

现在,如果我运行它,我得到:

{1: 'UC2C_jShtL725hvbm1arSV9w', 2: 'UC2C_jShtL725hvbm1arSV9w'}
<HttpError 404 when requesting https://www.googleapis.com/youtube/v3/channels?fields=items%2Fid%2Citems%2FbrandingSettings%2Fchannel&alt=json&part=id%2CbrandingSettings&id=UC2C_jShtL725hvbm1arSV9w&key=foobar returned "Not Found">
<HttpError 404 when requesting https://www.googleapis.com/youtube/v3/channels?fields=items%2Fid%2Citems%2FbrandingSettings%2Fchannel&alt=json&part=id%2CbrandingSettings&id=UC2C_jShtL725hvbm1arSV9w&key=foobar returned "Not Found">

奇怪。对我来说似乎很奇怪的是,如果我尝试向这些链接发出简单请求(只需在浏览器中剪切和粘贴URL),服务器就会像往常一样返回数据。

1 个答案:

答案 0 :(得分:0)

似乎这个问题已在最新版本的python库中修复。

但是,如果某人仍需要解决它,或者正在使用其他环境(如iOS或Android),那就是解决方案。

似乎google在单个批量网址之前使用过,这是:

https://www.googleapis.com/batch

这在我的应用程序中运行良好,直到它突然停止。似乎解决方案是将批处理调用的URL更改为:

https://www.googleapis.com/batch/youtube/v3 (适用于youtube apis)

通常google api对象会公开一个允许更改此值的属性,但如果没有,则可以在源代码中更改。