Python 빠른 시작

빠른 시작에서는 Google Workspace API

Google Workspace 빠른 시작에서는 API 클라이언트 라이브러리를 사용하여 인증 및 승인 흐름의 세부 정보를 확인하세요. 따라서 자체 앱에 클라이언트 라이브러리를 사용합니다. 이 빠른 시작에서는 테스트에 적합한 간소화된 인증 접근 방식 환경입니다 프로덕션 환경의 경우 인증 및 승인 이전 액세스 사용자 인증 정보 선택 선택할 수 있습니다.

Drive 라벨 API

목표

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

기본 요건

  • 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. 확인을 클릭합니다. 새로 생성된 사용자 인증 정보가 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 계정에 로그인하지 않았다면 로그인하라는 메시지가 표시됩니다. 여러 계정에 로그인되어 있는 경우 승인에 사용할 계정 1개를 선택합니다.
    2. 수락을 클릭합니다.

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

다음 명령어로 요청을 전송하는 첫 번째 Python 애플리케이션을 Drive 라벨 API

다음 단계