python helper类来简化与googleapi的交互。基于python的google api客户端。
google-api-helper的Python项目详细描述
google api助手帮助简化对googleapi的访问,包括使用oauth2和工厂方法创建api服务的身份验证。也就是说,创建compute a p i服务并不坏,但仍需要一些代码:
importgoogleapiclient.discoveryfromoauth2client.service_accountimportServiceAccountCredentialscredentials=ServiceAccountCredentials.from_json_keyfile_name("service_account.json",["https://www.googleapis.com/auth/compute"])compute=googleapiclient.discovery.build('compute','v1',credentials=credentials)
使用google api helper,这是一个单行程序:
fromgoogleapiimportGoogleApicompute=GoogleApi.compute().with_service_account_file("service_account.json")
使用oauth2流也很简单
fromgoogleapiimportGoogleApicompute=GoogleApi.compute().with_oauth2_flow("client_secret.json")
python-google-api客户端还可以重试包含的服务器错误,但不限于速率限制。因此,您进行的每个api调用都需要实现指数退避。这是通过使用google api助手自动完成的。
fromgoogleapiimportGoogleApicompute=GoogleApi.compute().with_oauth2_flow("client_secret.json")# directly using the api service without retriescompute.service.instances().list(project="my-gcp-project",zone="europe-west1-d").execute()# wrapper including retries for rate limiting and server side errorscompute.instances().list(project="my-gcp-project",zone="europe-west1-d").execute()
安装
将google api helper添加到requirements.txt或模块需求中,或通过pip安装:
pip install google-api-helper
快速启动
在python代码中导入googleapi
fromgoogleapiimportGoogleApi
从工厂方法创建API或自行指定:
compute=GoogleApi.compute()drive=GoogleApi.drive()gmail=GoogleApi("gmail","v1",["https://mail.google.com/"])
使用OAuth2进行身份验证
# use Compute Engine or App Engine default credentialscompute.with_application_credentials()# use a service account to access a users drivedrive.with_service_account_file("service_account.json","test@example.com")# or run a oauth2 flow to ask the user for credentialsgmail.with_oauth2_flow("client_secret.json")
并调用api
instances=compute.instances().list(project="project-id",zone="europe-west1-d").execute()drive_files=drive.files().list(q="name='test'").execute()messages=gmail.users().messages().list(userId="me").execute()
构建和发布
python setup.py bdist_wheel --universal python -m twine upload dist/*