[python] python-dotenv를 사용하여 구글 인증 설정하기

이 블로그 포스트에서는 파이썬에서 구글 인증을 설정하는 방법에 대해 알아보겠습니다. 구글 API를 사용하려면 인증 토큰이 필요하며, python-dotenv 라이브러리를 사용하여 환경 변수에 저장된 인증 정보를 사용할 수 있습니다.

python-dotenv 설치하기

먼저 python-dotenv를 설치해야 합니다. 아래의 명령어를 사용하여 설치할 수 있습니다.

pip install python-dotenv

환경 변수 저장하기

구글 인증 정보를 환경 변수에 저장해야 합니다. 프로젝트 디렉토리에 .env 파일을 생성하고 다음과 같은 형식으로 인증 정보를 입력합니다.

GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret

위에서 생성한 .env 파일을 환경 변수에 로드하기 위해 파이썬 스크립트 상단에 다음 코드를 추가합니다.

from dotenv import load_dotenv
load_dotenv()

구글 인증 설정하기

이제 구글 인증을 설정할 수 있습니다. 다음은 예시 코드입니다.

import os
from google.auth import credentials
from google.auth.transport.requests import Request
from google.oauth2 import id_token, service_account

def get_google_creds():
    creds = None
    if os.getenv('GOOGLE_CLIENT_ID') and os.getenv('GOOGLE_CLIENT_SECRET'):
        credentials_json = {
            "type": "service_account",
            "project_id": "your_project_id",
            "private_key_id": "your_private_key_id",
            "private_key": "your_private_key",
            "client_email": "your_client_email",
            "client_id": "your_client_id",
            "auth_uri": "https://accounts.google.com/o/oauth2/auth",
            "token_uri": "https://accounts.google.com/o/oauth2/token",
            "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
            "client_x509_cert_url": "your_client_x509_cert_url"
        }
        creds = service_account.Credentials.from_service_account_info(credentials_json)
    return creds

def authenticate():
    creds = get_google_creds()
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = id_token.fetch_id_token(Request(), os.getenv('GOOGLE_CLIENT_ID'))
            creds = flow.credentials
    return creds

# 인증 토큰 가져오기
credentials = authenticate()
access_token = credentials.token

위 코드에서는 .env 파일에서 구글 인증 정보를 읽어온 후, 인증 토큰을 가져오는 함수를 정의하고 있습니다. 이렇게 가져온 토큰을 이용하여 구글 API와의 통신에 사용할 수 있습니다.

결론

python-dotenv 라이브러리를 사용하여 파이썬에서 구글 인증을 설정하는 방법을 알아보았습니다. 이렇게 설정한 인증 정보를 활용하여 구글 API와의 통신을 원할하게 할 수 있습니다. 추가적인 정보는 python-dotenv 공식 문서를 참고하시기 바랍니다.