개요
Google Cloud API를 Python에서 사용하는 방법에 대해서 알아본다
모듈
인증을 위한 google.auth.credentials 모듈과 클라이언트 생성을 위한 googleapiclient 모듈이 필요하다.
- Google Auth Credentials: https://google-auth.readthedocs.io/en/latest/index.html
- Google API Client: https://github.com/googleapis/google-api-python-client
import googleapiclient.discovery as discovery
from google.auth import service_account
인증
google.auth 모듈을 통해 인증 가능한 방법은 다음과 같다.
-
Google
Application Default Credentials
- JWT 서명 및 인증
- Google ID Tokens 생성
-
ID Tokens
인증 및 디코딩 -
Google
Service Account Credentials
-
Google
Impersonated Credentials
-
Google Compute Engine Credentials
-
Google App Engine Standard Credentials
- Requests, urllib3, gRPC
Google Service Account로 인증하는 경우 다음과 같이 사용할 수 있다.
cred = service_account.Credentials.from_service_account_info(KEY_DATA)
KEY_DATA는 json 형식의 문서로, Credential Type과 Project ID, Private Key 정보 등이 포함되어 있다.
API 호출
위에서 인증 과정을 통해 생성한 인증 정보를 파라미터로 넘겨 클라이언트를 호출할 수 있다. 클라이언트 호출 시 discovery 모듈을 사용한다.
compute = discovery.build('compute', 'v1', credentials=cred)
discovery.build의 기본형은 다음과 같은 인자를 사용할 수 있다. serviceName으로 사용하고자 하는 API 이름(googleapiclient 모듈에서 정확한 이름을 확인해야 함)과 사용 가능한 API 버전을 사용하고, credentials 옵션에 Service Account 정보를 바탕으로 생성한 객체를 전달한다.
def build(
serviceName,
version,
http=None,
discoveryServiceUrl=DISCOVERY_URI,
developerKey=None,
model=None,
requestBuilder=HttpRequest,
credentials=None,
cache_discovery=True,
cache=None,
client_options=None,
adc_cert_path=None,
adc_key_path=None,
num_retries=1,
):
클라이언트를 빌드하면 API 문서를 참고해서 사용 가능한 API를 호출한다. 예를 들어 GCE 인스턴스 목록은 다음과 같이 조회할 수 있다.
ZONES = ["asia-northeast3-a", "asia-northeast3-b", "asia-northeast3-c"]
result = []
for zone in ZONES:
res = compute.instances().list(project=cred.get('project_id'), zone=zone).execute()
try:
for instance in res['items']:
result.append(instance)
except KeyError as e:
print(e, ' No Instance in current zone: {}'.format(zone))
except Exception as e:
print(e)
finally:
pass