如何在Python中使用服务帐户凭据创建Google表格?

问题描述 投票:0回答:1

我创建了Service Account Credentials here,并获得了json键service.json

然后我尝试:

from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
credentials = service_account.Credentials.from_service_account_file(
        'service.json', scopes=SCOPES)

drive = build('drive', 'v3', credentials=credentials)
file_metadata = {
    'name': 'sampleName',
    'parents': ['#### folderId ###'],
    'mimeType': 'application/vnd.google-apps.spreadsheet',
}
res = drive.files().create(body=file_metadata).execute()
print(res)

出现错误:

<HttpError 403 when requesting https://www.googleapis.com/drive/v3/files?alt=json returned "Insufficient Permission: Request had insufficient authentication scopes.">

{
 "error": {
  "errors": [
   {
    "domain": "usageLimits",
    "reason": "dailyLimitExceededUnreg",
    "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup.",
    "extendedHelp": "https://code.google.com/apis/console"
   }
  ],
  "code": 403,
  "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup."
 }
}

我发现没有Auth标头,我是匿名的,匿名使用的配额为零。如何设置标头,或者出现此错误的原因是其他原因?

我想要的是从任何计算机的gdrive文件夹中使用python创建电子表格,而无需单击某处来授予访问权限。

python google-drive-api google-sheets-api google-authentication google-console-developer
1个回答
0
投票
  • 您想使用带有服务帐户的Drive API v3创建新的电子表格。
  • 您想在您的Google帐户的Google云端硬盘的特定文件夹中创建新的电子表格。
  • 您想使用带有python的googleapis实现此目的。
  • 您已经可以使用Drive API。

如果我的理解正确,那么这个答案如何?请认为这只是几个可能的答案之一。

修改点:

  • 我认为您的脚本中需要修改作用域,才能使用Drive API创建文件。在这种情况下,如何使用https://www.googleapis.com/auth/drive
  • 为了在您的Google帐户的Google云端硬盘的特定文件夹中创建新的电子表格,首先,需要与该服务帐户的电子邮件共享Google云端硬盘中的文件夹。这样,将使用服务帐户将新的电子表格创建到Google云端硬盘的特定文件夹中。请注意这一点。

修改的脚本:

修改脚本后,请如下进行修改。

from googleapiclient.discovery import build  # Added
from google.oauth2 import service_account

SCOPES = ['https://www.googleapis.com/auth/drive']  # Modified
credentials = service_account.Credentials.from_service_account_file('service.json', scopes=SCOPES)

drive = build('drive', 'v3', credentials=credentials)
file_metadata = {
    'name': 'sampleName',
    'parents': ['#### folderId ###'],
    'mimeType': 'application/vnd.google-apps.spreadsheet',
}
res = drive.files().create(body=file_metadata).execute()
print(res)
  • 关于#### folderId ###,请设置与服务帐户的电子邮件共享的文件夹ID。

注意:

  • 如果要同时使用Sheets API和Drive API,请使用SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/spreadsheets"]
  • 在这种情况下,新的电子表格将直接创建到您的Google云端硬盘中的文件夹中。这样您就可以通过浏览器看到它。
    • 如果在服务帐户的云端硬盘中的文件夹中创建了新的电子表格,则需要为您的Google帐户创建权限。请注意这一点。在这种情况下,我认为this thread是有用的。

参考:

如果我误解了你的问题,而这不是你想要的方向,我深表歉意。

© www.soinside.com 2019 - 2024. All rights reserved.