-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnotion_bck.py
70 lines (55 loc) · 1.94 KB
/
notion_bck.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
notion_back - backup notion automagically
Author: pronex
"""
import os
import datetime
import json
import requests
import structlog
from config import initialize_global_config, GLOBAL_CONFIG
_logger = structlog.get_logger() # logging
initialize_global_config() # initialize global config
# setup requests
headers = {
'Authorization': f'Bearer {GLOBAL_CONFIG.notion_token}',
'Notion-Version': '2022-06-28',
'Content-Type': 'application/json',
}
# setup path
BCK_FOLDER_NAME = "bck_out_"
BCK_FOLDER_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), BCK_FOLDER_NAME)
# main
# following https://notionbackups.com/blog/automated-notion-backup-api
def backup() -> None:
"""
Run the backup process.
"""
# setup folder
timestamp = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
folder = BCK_FOLDER_PATH + timestamp
os.mkdir(folder)
# search all pages that can be found
response = requests.post('https://api.notion.com/v1/search', headers=headers, timeout=10)
# retrieve block children
for block in response.json()['results']:
with open(f'{folder}/{block["id"]}.json', 'w', encoding="utf-8") as file:
file.write(json.dumps(block))
child_blocks = requests.get(f'https://api.notion.com/v1/blocks/{block["id"]}/children',
headers=headers, timeout=10)
if child_blocks.json()['results']:
os.mkdir(folder + f'/{block["id"]}')
for child in child_blocks.json()['results']:
with open(f'{folder}/{block["id"]}/{child["id"]}.json',
'w', encoding="utf-8") as file:
file.write(json.dumps(child))
# entrypoint for the app
if __name__ == "__main__":
_logger.info("Starting ...")
try:
backup()
except: # pylint: disable=bare-except
_logger.error("Backup failed!")
_logger.info("Finished.")