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

F. *_*nim 1 python google-authentication google-drive-api google-console-developer google-sheets-api

Service Account Credentials 我在这里创建并得到了 json key 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)
Run Code Online (Sandbox Code Playgroud)

有错误:

<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."
 }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Tan*_*ike 5

  • 您想要使用 Drive API v3 和服务帐户创建新的电子表格。
  • 您想要在 Google 帐户的 Google Drive 的特定文件夹中创建新的电子表格。
  • 您希望使用 googleapis 和 Python 来实现此目的。
  • 您已经能够使用 Drive API。

如果我的理解是正确的,这个答案怎么样?

修改点:

  • 我认为在您的脚本中,需要修改范围才能使用 Drive API 创建文件。在这种情况下,如何使用https://www.googleapis.com/auth/drive
  • 为了在您的 Google 帐户的 Google Drive 的特定文件夹中创建新的电子表格,首先需要将您的 Google Drive 中的文件夹与服务帐户的电子邮件共享。这样,新的电子表格将使用服务帐户创建到您的 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)
Run Code Online (Sandbox Code Playgroud)
  • 关于#### folderId ###,请设置与服务帐号的邮箱共享的文件夹ID。

笔记:

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

参考: