시트 생성 및 업데이트 - 시트 업데이트
파일 로드 및 저장
def load_file_to_dict(path):
if os.path.exists(path):
with open(path, "r") as f:
return dict(json.load(f))
return dict()
def save_file_to_dict(path, cache):
with open(path, "w", encoding="utf-8") as f:
json.dump(cache, f, ensure_ascii=False, indent=4)
- 시트 생성과 업데이트에 둘 다 쓰이고 원하는 구조가 key : value 이기에 함수화 하였다.
시트 업데이트
시트 업데이트 같은 경우 두가지 dictionary 구조의 json 파일을 이용한다.
- tabs_dict : 프로젝트 명이 변경될 경우 시트 탭 타이틀이 변경되어야 한다. 구글 시트의 각 탭에는 gid라는 값이 존재하는데 이 값이 시트의 각 탭의 유일성을 보장해주기에 이 값을 활용한다. {gid : 탭 타이틀}
- update_dict : 노션의 데이터베이스의 '최종 편집 일시' 속성을 이용한다. 그리고 노션의 데이터베이스에서 새로 row(페이지)가 생성되면 각 row마다 페이지 링크가 있고 링크마다 id가 존재한다. {페이지 id : 최종 편집 일시} 를 저장해두어 만약 페이지 id 값이 저장되어 있지 않거나 현재 노션에 표기된 '최종 편집 일시'와 저장되어 있는 값이 다르다면 업데이트가 이루어진 것이고 시트에도 반영되어야 할 것이다.
# 시트 업데이트
def update_sheets():
# === 기존 기록 로드 ===
tabs_dict = load_file_to_dict(SHEET_TABS_INFO)
# === 업데이트 ===
update_dict = load_file_to_dict(PROJECT_UPDATE_INFO)
# 시트 연결
sheets = get_sheets_service()
# === 노션 데이터 불러오기
results = notion.databases.query(database_id=PROJECT_DB_ID)["results"]
# === 시트 복사 및 데이터 삽입
for page in results:
props = page["properties"]
sheet_url = props["sheet url"]['url']
last_edited_time = props["최종 편집 일시"]["last_edited_time"]
page_id = page["id"]
if page_id in update_dict and update_dict[page_id] == last_edited_time:
continue
# 시트 생성이 되지 않은 프로젝트
if sheet_url == None:
continue
update_dict[page_id] = last_edited_time
project_name = props["프로젝트명"]["title"][0]["plain_text"]
tab_title = f"{project_name}_결산"
gid = props["sheet url"]["url"].split('gid=')[-1]
if tabs_dict[gid] != tab_title:
# 탭 타이틀 최신화
tabs_dict[gid] = tab_title
# 시트 탭 이름 변경
sheets.spreadsheets().batchUpdate(
spreadsheetId=GOOGLE_SHEET_ID,
body={
"requests": [
{
"updateSheetProperties": {
"properties": {
"sheetId": gid,
"title": tab_title
},
"fields": "title"
}
}
]
}
).execute()
project_info = {
"project_name": project_name,
"project_type": props["프로젝트 형태"]["select"]["name"] if props["프로젝트 형태"]["select"] else '-',
"business_manager": props["영업 담당자"]["multi_select"][0]["name"] if len(props["영업 담당자"]["multi_select"]) != 0 else '-',
"release_date": props["납품일"]["date"]["start"] if props["납품일"]["date"] else '',
"catalog_no": props["Cat No."]["rich_text"][0]["plain_text"] if len(props["Cat No."]["rich_text"]) != 0 else '',
"unit_quantity": props["unit quantity"]["number"] if props["unit quantity"]["number"] else 0,
"extra_quantity": props["extra quantity"]["number"] if props["extra quantity"]["number"] else 0,
"vinyl_set": props["vinyl set"]["select"]["name"] if props["vinyl set"]["select"] else '-',
}
# 값 삽입
sheets.spreadsheets().values().batchUpdate(
spreadsheetId=GOOGLE_SHEET_ID,
body={
"valueInputOption": "USER_ENTERED",
"data": [
{"range": tab_title + "!D4", "values": [[project_info["project_name"]]]},
{"range": tab_title + "!D6", "values": [[project_info["catalog_no"]]]},
{"range": tab_title + "!D7", "values": [[project_info["project_type"]]]},
{"range": tab_title + "!D8", "values": [[project_info["business_manager"]]]},
{"range": tab_title + "!F6", "values": [[project_info["release_date"]]]},
{"range": tab_title + "!I5", "values": [[project_info["unit_quantity"]]]},
{"range": tab_title + "!I6", "values": [[project_info["extra_quantity"]]]},
{"range": tab_title + "!I7", "values": [[project_info["vinyl_set"]]]},
]
}
).execute()
time.sleep(3)
# 기록 저장
save_file_to_dict(SHEET_TABS_INFO, tabs_dict)
save_file_to_dict(PROJECT_UPDATE_INFO, update_dict)
print("✅ 시트 업데이트 완료")'프로젝트' 카테고리의 다른 글
| 노션 - 구글 Sheet 연동 (5) (0) | 2025.08.20 |
|---|---|
| 노션 - 구글 Sheet 연동 (3) (2) | 2025.08.18 |
| 노션 - 구글 Sheet 연동 (2) (1) | 2025.07.23 |
| 노션 - 구글 Sheet 연동 (1) (1) | 2025.07.21 |