kel*_*bug 5 python google-api google-api-python-client service-accounts google-sheets-api
我正在尝试使用 python 打开私人谷歌工作表。这里的最终目标是将私有工作表数据读入 json 对象。我已确保创建一个谷歌云项目,启用 API 和服务帐户。服务帐户电子邮件已共享并添加为编辑者。我还为桌面应用程序创建了 OAuth 密钥。这是必需的,因为该文件是私有的。
我知道我需要以某种方式请求一个令牌来访问工作表 API,但我不知道如何创建请求并利用client_secret从 OAuth 密钥生成的文件。我认为 googleAPI 会有一个可以直接传递此文件的函数,但我迷失在文档中。
任何见解将不胜感激!
您需要做的就是向库提供您应该从 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
Run Code Online (Sandbox Code Playgroud)
我所知道的使用 python 进行服务帐户身份验证的最好示例是Google Analytics 快速入门。 如果您在更改 Google Sheets 时遇到任何问题,请告诉我,我可以尝试提供帮助。
调用它应该是这样的。
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)
Run Code Online (Sandbox Code Playgroud)
如何创建clientSecret.json 记得启用libary下的google Sheets api
| 归档时间: |
|
| 查看次数: |
3852 次 |
| 最近记录: |