【问题标题】:How to use a service account to authorize google sheets?如何使用服务帐户授权谷歌表格?
【发布时间】:2021-11-10 06:49:57
【问题描述】:

我正在尝试使用 python 打开一个 private google 工作表。这里的最终目标是将私有工作表数据读入 json 对象。我确保创建了一个谷歌云项目,启用 API 和服务帐户。服务帐户电子邮件已共享并添加为编辑器。我还为桌面应用程序创建了 OAuth 密钥。这是必需的,因为文件是私有的。

我知道我需要以某种方式请求一个令牌以用于访问工作表 API,但我不知道如何创建请求并利用从 OAuth 密钥生成的 client_secret 文件。我想 googleAPI 会有一个函数,你可以直接传递这个文件,但我迷失在文档中。

任何见解将不胜感激!

【问题讨论】:

    标签: python google-api google-sheets-api google-api-python-client service-accounts


    【解决方案1】:

    您需要做的就是向库提供您应该从 Google 云控制台下载的 clientSecret.json 文件的位置。此方法应该为您构建服务,您可以向 api 发出请求。它将处理所有授权。

    from apiclient.discovery import build
    from oauth2client.service_account import ServiceAccountCredentials
    
    
    def get_service(api_name, api_version, scopes, key_file_location):
        """Get a service that communicates to a Google API.
    
        Args:
            api_name: The name of the api to connect to.
            api_version: The api version to connect to.
            scopes: A list auth scopes to authorize for the application.
            key_file_location: The path to a valid service account JSON key file.
    
        Returns:
            A service that is connected to the specified API.
        """
    
        credentials = ServiceAccountCredentials.from_json_keyfile_name(
                key_file_location, scopes=scopes)
    
        # Build the service object.
        service = build(api_name, api_version, credentials=credentials)
    
        return service
    

    我所知道的使用 python 进行服务帐户身份验证的最佳示例是 Google analytics quickstart 如果您在为 google 表格更改它时遇到任何问题,请告诉我,我可以尝试并提供帮助。

    调用它应该是这样的。

    def main():
        # Define the auth scopes to request.
        scope = 'https://www.googleapis.com/auth/spreadsheets'
        key_file_location = '<REPLACE_WITH_JSON_FILE>'
    
        # Authenticate and construct service.
        service = get_service(
                api_name='sheets',
                api_version='v4',
                scopes=[scope],
                key_file_location=key_file_location)
    
        data = your_method_to_call_sheets(service)
    

    How to create clientSecret.json记得开启libary下的google sheet api

    【讨论】:

    • 太棒了,工作!对于其他苦苦挣扎的人,我使用此代码检索工作表数据: sheet = service.spreadsheets() result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE_NAME).execute() values = result。获取('值',[])
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    相关资源
    最近更新 更多