IAM 데이터베이스 인증 및 asyncpg를 사용하여 연결

이 스니펫은 Python asyncpg 드라이버를 사용하여 안전한 비동기 연결 풀을 만드는 방법을 보여줍니다. 비밀번호로 자동 새로고침되는 OAuth2 액세스 토큰을 제공하는 IAM 데이터베이스 인증을 사용하여 인스턴스에 연결합니다.

코드 샘플

Python

AlloyDB에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import asyncpg

import google.auth
from google.auth.transport.requests import Request

    # initialize Google Auth credentials
    credentials, _ = google.auth.default(
        scopes=["https://www.googleapis.com/auth/cloud-platform"]
    )

    def get_authentication_token() -> str:
        """Get OAuth2 access token to be used for IAM database authentication"""
        # refresh credentials if expired
        if not credentials.valid:
            request = Request()
            credentials.refresh(request)
        return credentials.token

    # ... inside of async context (function)
    async with asyncpg.create_pool(
        user=user,  # your IAM db user, e.g. service-account@project-id.iam
        password=get_authentication_token,  # callable to get fresh OAuth2 token
        host=ip_address,  # your AlloyDB instance IP address
        port=5432,
        database=db,  # your database name
        # Because this connection uses an OAuth2 token as a password, you must
        # require SSL, or better, enforce all clients speak SSL on the server
        # side. This ensures the OAuth2 token is not inadvertantly leaked.
        ssl="require",
    ) as pool:
        # acquire connection from native asyncpg connection pool
        async with pool.acquire() as conn:
            time = await conn.fetchrow("SELECT NOW()")
            print("Current time is ", time[0])

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저 참조하기