Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 通过服务帐户通过域范围的委派模拟用户访问Google Sheets API失败 示例代码 问题行为_Python_Python 3.x_Google Sheets_Google Oauth_Service Accounts - Fatal编程技术网

Python 通过服务帐户通过域范围的委派模拟用户访问Google Sheets API失败 示例代码 问题行为

Python 通过服务帐户通过域范围的委派模拟用户访问Google Sheets API失败 示例代码 问题行为,python,python-3.x,google-sheets,google-oauth,service-accounts,Python,Python 3.x,Google Sheets,Google Oauth,Service Accounts,最后一行失败,客户端未经授权使用此方法检索访问令牌,或者客户端未被授权使用任何请求的作用域。 预期行为 最后一行提供了一个用于GoogleSheets访问的对象 附加信息 已为服务帐户启用域范围的委派,subject帐户位于域上 工作表与科目科目共享 当我不提供主题并直接与服务帐户共享该表时,它会起作用 环境 python==3.6.9 pygsheets==2.0.3.1 googleauth==1.6.3 在使用域范围委托时考虑 默认情况下不启用域范围的委派。要允许它,您需要遵循中描述

最后一行失败,
客户端未经授权使用此方法检索访问令牌,或者客户端未被授权使用任何请求的作用域。

预期行为 最后一行提供了一个用于GoogleSheets访问的对象

附加信息
  • 已为服务帐户启用域范围的委派,
    subject
    帐户位于域上
  • 工作表与
    科目
    科目共享
  • 当我不提供
    主题
    并直接与服务帐户共享该表时,它会起作用
环境

  • python==3.6.9
  • pygsheets==2.0.3.1
  • googleauth==1.6.3
  • 在使用域范围委托时考虑 默认情况下不启用域范围的委派。要允许它,您需要遵循中描述的步骤

  • 步骤:在GCP控制台中:
    • 您需要为每个要用于此目的的服务帐户激活复选框
      Enable G Suite Domain-wide Delegation
      要使用服务帐户模拟用户,需要在管理控制台中授予必要的权限
  • 在管理控制台中:
    • 必须在管理控制台中授权服务帐户在模拟用户时所需的任何作用域
    • 为此,请转到
      主菜单>安全>API控件。
    • 通过其
      客户ID
      添加(如果尚未添加)感兴趣的服务帐户,为其提供所需的所有范围并进行授权
    • 如果需要,您可以在稍后的阶段随时修改作用域

    如果您的请求在没有主题的情况下工作,但失败了-很可能您没有在
    安全->API CONTROLS
    下的管理控制台中为域范围的委派启用必要的作用域,请参阅@主人:不知道你是什么意思。@ziganotschka确实是这样。你愿意把它写下来作为回答吗?
    from google.oauth2 import service_account 
    import pygsheets
    
    creds = service_account.Credentials.from_service_account_file(
        'my/path/to/credentials.json',
        scopes=('https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/drive'),
        subject='account@mydomain.com'
    )
    pg = pygsheets.authorize(custom_credentials=creds)
    pg.open_by_url('https://docs.google.com/spreadsheets/d/my_spreadsheet_id/edit#gid=my_sheet_id')