【问题标题】:How to create Google Sheets using Service Account Credential in Python?如何在 Python 中使用服务帐户凭据创建 Google 表格?
【发布时间】:2020-06-27 11:46:08
【问题描述】:

我创建了Service Account Credentials here 并得到了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)

出现错误:

<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】:
    • 您想通过服务帐户使用 Drive API v3 创建新的电子表格。
    • 您想在您的 Google 帐户的 Google Drive 的特定文件夹中创建新的电子表格。
    • 您希望使用 googleapis 和 python 来实现此目的。
    • 您已经能够使用 Drive API。

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

    修改点:

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

    修改脚本:

    当你的脚本被修改时,请按如下方式修改。

    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 Drive 中的文件夹中。所以你可以通过浏览器看到它。
      • 如果在服务帐户的 Drive 中的文件夹中创建新的电子表格,则需要为您的 Google 帐户创建权限。请注意这一点。在这种情况下,我认为this thread 很有用。

    参考资料:

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

    【讨论】:

    • @F.沃斯尼姆欢迎。很高兴您的问题得到解决。