프로그래밍/python

[Python] python으로 notion에 글쓰기

장경훈 2023. 11. 7. 01:56

1. 관련 라이브러리 install

pip install notion

 

 

2. 베이스 코드 확인

from notion.client import NotionClient

#노션 Token 입력
client = NotionClient(token_v2="<token_v2>")

#글쓰려고 하는 페이지 링크 입력
page = client.get_block("https://www.notion.so/myorg/Test-c0d20a71c0944985ae96e661ccc99821")
 
print("The old title is:", page.title)
 
page.title = "The title has now changed, and has *live-updated* in the browser!"

 

3. 토큰 확인 방법

Notion 페이지 -> F12(chrome) -> 애플리케이션 -> 쿠키 -> www.notion.so  -> token_v2

 

4. 페이지에 글쓰는 코드 

from notion.client import *
from notion.block import *
 
# 생성할 표에 들어가는 데이터 JSON형식 
def get_collection_schema():
    return {
        "title" : {"name" : "title", "type" : "text"},
        "date" : {"name" : "date" , "type" : "text"},
    }
 
token = "" # 토큰 입력
url = "" # 글쓰려고 하는 노션 페이지 url
 
#토큰 및 페이지 설정
client = NotionClient(token_v2 = token)
page = client.get_block(url)
 
# 위에서 선택한 페이지에 글쓰려고 하는 페이지 생성 (스키마는 위의 구조와 동일 )
child_page = page.children.add_new(CollectionViewPageBlock)
child_page.collection = client.get_collection(
    client.create_record('collection', parent=child_page, schema=get_collection_schema())
)
 
child_page.title = "이상탐지" # 페이지 제목입니다.

row = child_page.collection.add_row() # row생성
row.title = '문제발생'
row.date='2022-02-02'

 
view = child_page.views.add_new(view_type='table') # 이렇게 view까지 선언

 

 

* There was an error (400) submitting the request""requests.exceptions.HTTPError: Invalid input 에러 발생시*

$ pip3 install -e git+https://github.com/c0j0s/notion-py#egg=notion

api가 바뀌면서 발생하는 문제이므로 위의 코드로 다운로드 하면 해결 완료