Data Engineering/Python

[Python/GoogleSpreadSheet API] GoogleSpreadSheet API 연동하기 (2)

YSY^ 2023. 9. 12. 21:49

구글 스프레드 시트 API 연동하기 (2)

이번 포스팅은 아래 포스팅에 이어 진행됩니다.

https://ysyblog.tistory.com/353

 

[Python/GoogleSpreadSheet API] GoogleSpreadSheet API 연동하기 (1)

구글 스프레드 시트 API 연동하기 오랜만에 개인프로젝트를 하고 있는데, 이 프로젝트에 구글 스프레드시트 API를 활용하게 되었다. 예전에 구글스프레드시트 API를 잘 썼지만.. 오랜만에 쓰려고

ysyblog.tistory.com

이번 포스팅에서는 지난 포스팅에서 받은 Credential 파일을 활용하여 API를 연동해보겠습니다.

구글 스프레드 시트 API 관련 패키지를 import 

import gspread
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build
from google.oauth2 import service_account
  • googleapiclient 패키지는 아래와 같은 코드를 활용하여 설치하여야 한다. (pip install googleapiclient 로 하면 설치가 안됩니다)
pip install google-api-python-client

 

Scope 세팅

  • Scope는 앱에 부여된 액세스 수준을 정의하는 것이다..
  • 아래와 같이 Scope를 세팅해준다. 형식은 무조건 리스트 형식이어야 하며 여러 Scope를 세팅할 수 있다.
scope = ['https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive']
범위 의미
https://www.googleapis.com/auth/drive Google Drive 파일 보기, 수정, 생성, 삭제
https://www.googleapis.com/auth/drive.file 이 앱에서 사용하는 특정 Google Drive 파일만 보고, 수정하고, 만들고, 삭제합니다.
https://www.googleapis.com/auth/drive.readonly 모든 Google Drive 파일을 보고 다운로드합니다.
https://www.googleapis.com/auth/spreadsheets 모든 Google Sheets 스프레드시트를 보고, 수정하고, 만들고, 삭제합니다.
https://www.googleapis.com/auth/spreadsheets.readonly 모든 Google Sheets 스프레드시트를 확인합니다.

출처 : https://developers.google.com/sheets/api/scopes?hl=ko 

Credential(자격 증명) 세팅

  • json_file_name에서는 이전 포스팅에서 다운 받았던 파일의 이름을 넣어주면 된다.
json_file_name = 'asset_management_key.json'
credentials = ServiceAccountCredentials.from_json_keyfile_name(json_file_name, scope)
gc = gspread.authorize(credentials)

creds = None
creds = service_account.Credentials.from_service_account_file(
    json_file_name, scopes=scope
)

 

Service Build

  • serviceName은 "sheet"로 세팅하고, version은 "v4" 로세팅한다.

CF) 현재 spreadsheet api version이 v4 이다.

gsheet_id = "{spreadsheet_id}"

service = build(
    serviceName="sheets",
    version="v4",
    credentials=creds,
    cache_discovery=False,
    )
spreadsheets = service.spreadsheets()

CF) spreadsheet id는 스프레드시트 링크에서 확인할 수 있다.

코드 정리

    def api_setting(self):
        scope = ['https://www.googleapis.com/auth/spreadsheets'
                 ,'https://www.googleapis.com/auth/drive']
        json_file_name = 'asset_management_key.json'
        credentials = ServiceAccountCredentials.from_json_keyfile_name(json_file_name, scope)
        gc = gspread.authorize(credentials)
        creds = None
        creds = service_account.Credentials.from_service_account_file(
            json_file_name, scopes=scope
        )

        service = build(
            serviceName="sheets",
            version="v4",
            credentials=creds,
            cache_discovery=False,
            )
        spreadsheets = service.spreadsheets()
        
        return spreadsheets

 

Spreadsheet 메타 데이터

  • 연동된 API로 spreadsheet의 메타 데이터를 불러올 수 있다.
  • 참고로 아래 코드는 sheetid가 0인 시트의 이름을 가져오고, 해당시트의 rowcount와 columncount를 가져오는 것이다.
sheet_metadata = spreadsheets.get(spreadsheetId=gsheet_id).execute()

# Find the sheet name corresponding to the sheetId
sheets = sheet_metadata.get('sheets', [])

for sheet in sheets:
    if sheet['properties']['sheetId'] == 0:
        sheet_name = sheet['properties']['title']
        break

# sheet_name : sheet1

grid_properties = sheet_metadata['sheets'][0]['properties']['gridProperties']
grid_properties

# {'rowCount': 1000, 'columnCount': 28}

CF) sheetId 아는 방법

  • 스프레드시트 주소에서 알 수 있다. gid= 다음에 있는 숫자가 sheet의 id이다.

 

728x90
반응형