Google索引API批处理请求AttributeError:“资源”对象没有属性“事件”

2024-09-28 15:29:50 发布

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

我试图使用谷歌索引批量请求,但它不工作。我做错了什么

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

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'

Tags: fromhttpsimportaddjsonhttpurlservice
1条回答
网友
1楼 · 发布于 2024-09-28 15:29:50

您可能会发现一些有用的参考资料:

下面是关于如何batch requests的解释。在Indexing API reference有python客户端库的参考资料

另请参见Indexing API Quickstart(所有参考文档都是从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)

相关问题 更多 >