Python 빠른 시작

빠른 시작에서는 Google Workspace API를 호출하는 앱을 설정하고 실행하는 방법을 설명합니다.

Google Workspace 빠른 시작은 API 클라이언트 라이브러리를 사용하여 인증 및 승인 흐름의 일부 세부정보를 처리합니다. 자체 앱에는 클라이언트 라이브러리를 사용하는 것이 좋습니다. 이 빠른 시작에서는 테스트 환경에 적합한 간소화된 인증 방식을 사용합니다. 프로덕션 환경의 경우 앱에 적합한 액세스 사용자 인증 정보를 선택하기 전에 인증 및 승인에 대해 알아보는 것이 좋습니다.

Drive Labels API에 요청을 수행하는 Python 명령줄 애플리케이션을 만듭니다.

목표

  • 환경을 설정합니다.
  • 클라이언트 라이브러리를 설치합니다.
  • 샘플을 설정합니다.
  • 샘플을 실행합니다.

기본 요건

  • Google 계정

환경 설정하기

이 빠른 시작을 완료하려면 환경을 설정하세요.

API 사용 설정

Google API를 사용하려면 먼저 Google Cloud 프로젝트에서 사용 설정해야 합니다. 단일 Google Cloud 프로젝트에서 하나 이상의 API를 사용 설정할 수 있습니다.
  • Google Cloud 콘솔에서 Drive Labels API를 사용 설정합니다.

    API 사용 설정

데스크톱 애플리케이션에 대한 사용자 인증 정보 승인

앱에서 최종 사용자를 인증하고 사용자 데이터에 액세스하려면 OAuth 2.0 클라이언트 ID를 하나 이상 만들어야 합니다. 클라이언트 ID는 Google OAuth 서버에서 단일 앱을 식별하는 데 사용됩니다. 앱이 여러 플랫폼에서 실행되는 경우 플랫폼마다 별도의 클라이언트 ID를 만들어야 합니다.
  1. Google Cloud 콘솔에서 메뉴 > API 및 서비스 > 사용자 인증 정보로 이동합니다.

    사용자 인증 정보로 이동

  2. 사용자 인증 정보 만들기 > OAuth 클라이언트 ID를 클릭합니다.
  3. 애플리케이션 유형 > 데스크톱 앱을 클릭합니다.
  4. 이름 입력란에 사용자 인증 정보의 이름을 입력합니다. 이 이름은 Google Cloud 콘솔에만 표시됩니다.
  5. 만들기를 클릭합니다. OAuth 클라이언트 생성 완료 화면이 나타나 새 클라이언트 ID와 클라이언트 비밀번호를 표시합니다.
  6. OK(확인)를 클릭합니다. 새로 만든 사용자 인증 정보가 OAuth 2.0 클라이언트 ID 아래에 표시됩니다.
  7. 다운로드한 JSON 파일을 credentials.json로 저장하고 작업 디렉터리로 파일을 이동합니다.

Google 클라이언트 라이브러리 설치

  • Python용 Google 클라이언트 라이브러리를 설치합니다.

      pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
    

대체 설치 옵션은 Python 라이브러리의 설치 섹션을 참조하세요.

샘플 구성

  1. 작업 디렉터리에서 quickstart.py라는 파일을 만듭니다.
  2. quickstart.py에 다음 코드를 포함합니다.

    import os.path
    
    from google.auth.transport.requests import Request
    from google.oauth2.credentials import Credentials
    from google_auth_oauthlib.flow import InstalledAppFlow
    from googleapiclient.discovery import build
    from googleapiclient.errors import HttpError
    
    # If modifying these scopes, delete the file token.json.
    SCOPES = ['https://www.googleapis.com/auth/drive.labels.readonly']
    
    def main():
      """Shows basic usage of the Drive Labels API.
    
        Prints the first page of the customer's Labels.
      """
      creds = None
      # The file token.json stores the user's access and refresh tokens, and is
      # created automatically when the authorization flow completes for the first
      # time.
      if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
      # If there are no (valid) credentials available, let the user log in.
      if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
          creds.refresh(Request())
        else:
          flow = InstalledAppFlow.from_client_secrets_file('credentials.json',
                                                          SCOPES)
          creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
          token.write(creds.to_json())
      try:
        service = build('drivelabels', 'v2', credentials=creds)
        response = service.labels().list(
            view='LABEL_VIEW_FULL').execute()
        labels = response['labels']
    
        if not labels:
          print('No Labels')
        else:
          for label in labels:
            name = label['name']
            title = label['properties']['title']
            print(u'{0}:\t{1}'.format(name, title))
      except HttpError as error:
        # TODO (developer) - Handle errors from Labels API.
        print(f'An error occurred: {error}')
    
    if __name__ == '__main__':
      main()
    

샘플 실행

  1. 작업 디렉터리에서 샘플을 빌드하고 실행합니다.

    python quickstart.py
    
  2. 샘플을 처음 실행하면 액세스를 승인하라는 메시지가 표시됩니다.

    1. 아직 Google 계정에 로그인하지 않았다면 로그인하라는 메시지가 표시됩니다. 여러 계정에 로그인되어 있는 경우 승인에 사용할 계정 하나를 선택합니다.
    2. 동의를 클릭합니다.

    승인 정보는 파일 시스템에 저장되므로 다음에 샘플 코드를 실행할 때는 승인하라는 메시지가 표시되지 않습니다.

Drive Labels API에 요청하는 첫 번째 Python 애플리케이션을 성공적으로 만들었습니다.

다음 단계