그동안의 노션 API 정복기 1~6 편을 소스 코드로 정리했습니다.
이런 친절한 블로거를 봤나 (여기서 봤다고 소문내기)
# 공통 코드
from dotenv import dotenv_values
from notion_client import Client
config = dotenv_values(".env")
notion_secret = config.get('NOTION_TOKEN')
notion = Client(auth=notion_secret)
# 모든 페이지를 조회해오는 코드, page_size 는 기호에 따라 조절
pages = notion.search(filter={"property": "object", "value": "page"}, page_size=10)
pprint(pages)
cursor_id = pages['next_cursor']
while pages['has_more']:
pages = notion.search(filter={"property": "object", "value": "page"},
start_cursor=cursor_id, page_size=10)
pprint(pages)
if pages['has_more']:
cursor_id = pages['next_cursor']
# Block의 내용을 바꾸는 코드
# 하기의 page_id 는 위 notion.search 로 불러온 pages 리스트에서 업데이트 할 블록들이 있는 페이지 id를 의미
page_id = '2c9258e1-43ed-4713-8895-123d42268d2f'
block_list = notion.blocks.children.list(block_id=page_id)
pprint(block_list)
# 첫번째 결과 Block의 값 변경을 원할 시 해당 id 와 rich_text 정보를 가져오기
target_block_id = block_list['results'][0]['id']
rich_text_temp = block_list['results'][0]['paragraph']['rich_text']
# plain_text의 값을 가져와서 원하는 문구로 변경
text_value = rich_text_temp[0]['plain_text']
text_value = text_value.replace('페퍼로니', '크러스트')
# 변경한 문구를 'plain_text' 와 'text'의 'content'에 반영
rich_text_temp[0]['plain_text'] = text_value
rich_text_temp[0]['text']['content'] = text_value
# Dictonary 형태로 rich_text 를 묶음
rich_text = {}
rich_text['rich_text'] = rich_text_temp
# 변경된 rich_text를 target_block_id 에 업데이트
notion.blocks.update(block_id=target_block_id, paragraph=rich_text)