반응형
'google cloud API'를 이용하려면 'service_secret_key.json'파일이 필수적으로 필요하다.
파일의 예시
{
"type": "service_account",
"project_id": "your-project",
"private_key_id": "your-key-id",
"private_key": "-----BEGIN PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END PRIVATE KEY-----\n",
"client_email": "your-mail@your-mail.iam.gserviceaccount.com",
"client_id": "your-client-id",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/your-url.iam.gserviceaccount.com"
}
구글 공식 문서에서 제공해준 구글 시트를 조회하는 함수
def get_gspread():
key_path = "./assets/service_secret_key.json" # json 파일이 있는 경로임
scope = [
"https://spreadsheets.google.com/feeds",
"https://www.googleapis.com/auth/drive",
]
credentials = ServiceAccountCredentials.from_json_keyfile_name(key_path, scope)
gc = gspread.authorize(credentials)
return gc
모종의 이유로 json 파일을 불러올 수 없는 경우를 위해
ServiceAccountCredentials.from_json_keyfile_name(key_path, scope)
함수 안쪽으로 이동해보았다.

_from_parsed_json_keyfile(keyfile_dict, scopes, token_uri=None, revoke_uri=None)
함수만 실행하면 한가지 과정을 넘길 수 있었던 것이었다.
그러기 위해서는 service_secret_key.json 파일을 프로젝트 내부로 옮겨 줄 필요가 있었음.
class GoogleAPI(Enum):
BOKSAN_RPA_SHEET_KEY = {
"type": "service_account",
"project_id": "yours",
"private_key_id": "yours",
"private_key": "-----BEGIN PRIVATE KEY-----\nyours\n-----END PRIVATE KEY-----\n",
"client_email": "yours@yours.iam.gserviceaccount.com",
"client_id": "yours",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"revoke_uri": "https://oauth2.googleapis.com/revoke",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/rpa-robot%40boksan-rpa-spreadsheet.iam.gserviceaccount.com",
"scopes": [
"https://spreadsheets.google.com/feeds",
"https://www.googleapis.com/auth/drive",
],
}
이 후 시트를 불러오는 함수를 변경했다.
def get_gspread():
api_json = GoogleAPI.RPA_SHEET_KEY.value
credentials = ServiceAccountCredentials._from_parsed_json_keyfile(
api_json, api_json["scopes"], token_uri=api_json["token_uri"], revoke_uri=api_json["revoke_uri"]
)
gc = gspread.authorize(credentials)
return gc
_from_parsed_json_keyfile(keyfile_dict, scopes, token_uri=None, revoke_uri=None) 를 직접 사용
반응형
'프로그래밍 > google api' 카테고리의 다른 글
| google driver api v3 pyinstaller not work (0) | 2023.02.20 |
|---|---|
| gspread 수식도 그대로 갖고 오는 옵션 (0) | 2022.10.04 |
| [Python] 구글 드라이브 API 연결해보기 (0) | 2022.06.14 |
| [Python] 구글 드라이브 API 초기설정 (0) | 2022.06.14 |