【问题标题】:Connect to Google API within my Organization在我的组织内连接到 Google API
【发布时间】:2021-11-05 16:08:32
【问题描述】:

我正在尝试使用 Python 从我组织内共享 Google 云端硬盘上的 Google 表格中提取数据。我有以下代码在我连接到我的个人 Google Drive 时有效,但在组织内无效。原因是我必须与我的服务帐户共享 Google 表格,但在共享驱动器中,我收到一条错误消息,指出我不允许在我的组织之外共享表格(它将我的服务帐户计为外部组织)。

我将如何解决这个问题?

def create_credentials():       
    credentials = Credentials.from_service_account_file(
            json_key,
            scopes=scopes)
    return gspread.authorize(credentials)

def read_spreadsheet(sample_spreadsheet_id, tab_index):    
    gc = create_credentials()
    gc = gc.open_by_key(sample_spreadsheet_id)
    values = gc.get_worksheet(tab_index).get_all_values()
    df = pd.DataFrame(values)
    df.columns = df.iloc[0]
    df.drop(df.index[0], inplace=True)         
    return df

df_grade = read_spreadsheet(sheet_id, 0 )

【问题讨论】:

    标签: python google-api


    【解决方案1】:

    服务帐号在用户背后使用。

    • 从 Google 管理控制台添加脚本所需的范围。 (采用 服务帐号 ID)
    • 启用 G Suite 域范围委派
    • 以 JSON 格式下载服务帐号私钥。
    var JSON_user = {
      "private_key": "your private key",
      "client_email": "your client email"
       };
    
      function getOAuthService(userId) {
      return OAuth2.createService("Service Account")
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')
      .setPrivateKey(JSON_user.private_key)
      .setIssuer(JSON_user.client_email)
      .setSubject(userId)
      .setPropertyStore(PropertiesService.getScriptProperties())
      .setParam('access_type', 'offline')
      .setScope('https://www.googleapis.com/auth/drive')
      .setParam('approval_prompt', 'auto');
       }
    

    现在您可以像这样模拟用户:

    var service = getOAuthService("user email to impersonate");
    

    【讨论】:

    • 这个去哪儿了?在我的创建凭据功能下?另外,这是 Python 吗?好像是js
    猜你喜欢
    • 2022-10-31
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    • 2020-10-03
    • 2015-01-12
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    相关资源
    最近更新 更多