Skip to content

Google python sdk

官方目前提供了两个 python sdk 客户端:

客户端库说明:https://cloud.google.com/apis/docs/client-libraries-explained?hl=zh-cn#google_api_client_libraries

如何开始

安装

bash
pip install google-api-python-client

创建服务账号及其密钥

https://googleapis.github.io/google-api-python-client/docs/oauth-server.html

  • 创建服务账号:在 IAM 页面服务账号子页面,点击创建服务账号
  • 添加密钥:在服务账号的操作选项中选择管理密钥,然后点击添加密钥;然后可将密钥文件保存或将内容存于数据库中供后续使用

通过服务账号鉴权调用 api 示例

python
from google.oauth2 import service_account
import googleapiclient.discovery

SCOPES = ['https://www.googleapis.com/auth/sqlservice.admin']
SERVICE_ACCOUNT_FILE = '/path/to/service.json'

credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
sqladmin = googleapiclient.discovery.build(
        'sqladmin', 'v1beta3', credentials=credentials)
response = sqladmin.instances().list(project='exemplary-example-123').execute()

print(response)

如何查找并使用一个产品的 api

以要获取 Cloud SQL 所有实例为例:

  1. API Explorer 查询 Cloud SQL 产品,进入其 api 文档
  2. api 文档 中可查看示例,以及各个方法

我的 GoogleAPI 集成

python
import httplib2
import google_auth_httplib2

from googleapiclient import discovery
from google.oauth2 import service_account
from sanic import Sanic


class GoogleAPI():
    def __init__(self, project):
        self.app = Sanic.get_app()
        self.project = project

    def _get_proxy_http(self):
        http = httplib2.Http(proxy_info=httplib2.ProxyInfo(
            httplib2.socks.PROXY_TYPE_HTTP,
            self.app.config.GOOGLE_HTTP_PROXY_IP,
            self.app.config.GOOGLE_HTTP_PROXY_PORT
        ))
        return http

    def _get_credentials(self, scopes):
        if scopes is None:
            scopes = ['https://www.googleapis.com/auth/cloud-platform']
        google_sa_key = f'google_sa_{self.project}'.upper()
        info = self.app.config[google_sa_key]
        credentials = service_account.Credentials.from_service_account_info(
            info, scopes=scopes)
        if 'admin.directory' in scopes[0]:
            credentials = credentials.with_subject(op@xxx.com')
        return credentials

    def discovery_build(self, product_code, product_version, scopes=None):
        credentials = self._get_credentials(scopes)
        http = self._get_proxy_http()
        authorized_http = google_auth_httplib2.AuthorizedHttp(
            credentials, http=http)
        service = discovery.build(
            product_code, product_version,
            # "compute", "v1",
            http=authorized_http,
        )
        # response = service.instances().list(
        #     project='test-xxx', zone='us-east4-c').execute()
        return service
  • 服务账号密钥存于库中,使用 from_service_account_info 引入
  • 国内访问 google api 需要走代理,代理通过 discovery.build() 函数的 http 参数进行配置