Google Indexing API Batch Request AttributeError: 'Resource' object has no attribute 'events'

Google Indexing API Batch Request AttributeError: 'Resource' object has no attribute 'events'

我正在尝试使用 Google 索引 BATCH 请求,但它不起作用。我做错了什么?

这是我的代码:没有合适的文档,所以我自己修改了它。但是,它会产生错误。

from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.http import BatchHttpRequest
import httplib2
from googleapiclient.discovery import build 
SCOPES = [ "https://www.googleapis.com/auth/indexing" ]
ENDPOINT = "https://indexing.googleapis.com/v3/urlNotifications:publish"

# service_account_file.json is the private key that you created for your service account.
JSON_KEY_FILE = "service_account_file.json"

credentials = ServiceAccountCredentials.from_json_keyfile_name(JSON_KEY_FILE, scopes=SCOPES)

service = build('indexing', 'v3', credentials=credentials)

def insert_event(request_id, response, exception):
    if exception is not None:
      print(exception)
    else:
      print(response)

batch = BatchHttpRequest(callback=insert_event)
batch.add(service.events().quickAdd(url="URL HERE", type="URL_UPDATED"))
batch.add(service.events().quickAdd(url="URL HERE", type="URL_UPDATED"))
batch.execute(http=http)

错误:

Traceback (most recent call last):
  File "c:\Users\Sofia\Downloads\ss.py", line 23, in <module>
    batch.add(service.events.quickAdd(url="https://jobsinwales.org/jobs/united-kingdom-jobs/co-225/", type="URL_UPDATED"))
AttributeError: 'Resource' object has no attribute 'events'

一些您可能会觉得有用的参考资料:

这里解释了如何 batch requests. There's reference material for the python client library at Indexing API reference

另见 Indexing API Quickstart (all the reference docs are dynamically generated from the same place)。

对您的代码进行了少量更新:

batch = service.new_batch_http_request(callback=insert_event)
batch.add(service.urlNotifications().publish(
    body={"url": "URL HERE", "type": "URL_UPDATED"}))
batch.add(service.urlNotifications().publish(
    body={"url": "URL HERE", "type": "URL_UPDATED"}))
batch.execute()

其次,虽然这应该按原样工作,但不推荐使用 oauth2client。您可能需要考虑升级到 google-auth 库。

from google.oauth2 import service_account

SCOPES = [ "https://www.googleapis.com/auth/indexing" ]
JSON_KEY_FILE = "service_account_file.json"

credentials = service_account.Credentials.from_service_account_file(
    JSON_KEY_FILE, scopes=SCOPES)