├── tests
├── __init__.py
├── fixtures.py
├── test_query.py
├── test_models.py
└── test_api.py
├── requirements.txt
├── .gitattributes
├── pyproject.toml
├── .gitignore
├── pytion
├── envs.py
├── __init__.py
├── exceptions.py
├── query.py
├── api.py
└── models.py
├── setup.py
├── CHANGELOG.md
├── README.md
└── LICENSE
/tests/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | requests>=2.26.0
2 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | # Auto detect text files and perform LF normalization
2 | * text=auto
3 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools"]
3 | build-backend = "setuptools.build_meta"
4 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | venv
2 | token
3 | __pycache__
4 | .idea
5 | misc*
6 | *tmp*
7 | *.log
8 | .pytest*
9 | conftest.py
10 | dist/
11 | *.egg-info/
12 | build
13 |
--------------------------------------------------------------------------------
/pytion/envs.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import logging
4 |
5 |
6 | # Base URL (mandatory)
7 | NOTION_URL = "https://api.notion.com/v1/"
8 |
9 | # Access token (optional)
10 | try:
11 | with open("token") as f:
12 | NOTION_SECRET = f.read()
13 | except FileNotFoundError:
14 | NOTION_SECRET = None
15 |
16 | # Current API Version (mandatory)
17 | NOTION_VERSION = "2022-06-28"
18 |
19 | # Logging settings (mandatory)
20 | LOGGING_BASE_LEVEL = logging.WARNING
21 | LOGGING_TO_CONSOLE = False
22 | # set `None` to do not logging into file
23 | LOGGING_FILE = None
24 |
25 | # every resource has `object` property (type declaration)
26 | # every resource has `id` property (UUIDv4)
27 | # every property is in snake_case only
28 | # temporal values - ISO 8601
29 | # 2020-08-12T02:12:33.231Z
30 | # 2020-08-12T02:12:33.231+00:00
31 | # 2020-08-12
32 |
33 | # empty strings ARE NOT supported. use `None` (python) or `null` (JSON)
34 |
--------------------------------------------------------------------------------
/tests/fixtures.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 |
4 | @pytest.fixture(scope="session")
5 | def root_page(no):
6 | return no.pages.get("878d628488d94894ab14f9b872cd6870")
7 |
8 |
9 | @pytest.fixture(scope="session")
10 | def page_some_texts(no):
11 | return no.pages.get("82ee5677402f44819a5da3302273400a")
12 |
13 |
14 | @pytest.fixture(scope="session")
15 | def little_database(no):
16 | return no.databases.get("0e9539099cff456d89e44684d6b6c701")
17 |
18 |
19 | @pytest.fixture(scope="session")
20 | def database_for_updates(no):
21 | return no.databases.get("bf6ee5f75f99433a9d65132c05b42958")
22 |
23 |
24 | @pytest.fixture(scope="session")
25 | def page_for_pages(no):
26 | return no.pages.get("1bc86cc1d6f24362a6c40c2c89b423cc")
27 |
28 |
29 | @pytest.fixture(scope="session")
30 | def page_for_updates(no):
31 | page = no.pages.get("36223246a20e42df8f9b354ed1f11d75")
32 | return page
33 |
34 |
35 | @pytest.fixture(scope="session")
36 | def database_for_pages(no):
37 | return no.databases.get("35f50aa293964b0d93e09338bc980e2e")
38 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | import setuptools
2 |
3 | with open("README.md", "r", encoding="utf-8") as fh:
4 | long_description = fh.read()
5 |
6 | setuptools.setup(
7 | name="pytion",
8 | version="1.3.5",
9 | author="Yegor Gomzin",
10 | author_email="slezycmex@mail.ru",
11 | description="Unofficial Python client for official Notion API",
12 | long_description=long_description,
13 | long_description_content_type="text/markdown",
14 | url="https://github.com/lastorel/pytion",
15 | project_urls={
16 | "Bug Tracker": "https://github.com/lastorel/pytion/issues",
17 | "Changelog": "https://github.com/lastorel/pytion/blob/main/CHANGELOG.md",
18 | },
19 | classifiers=[
20 | "Programming Language :: Python :: 3.7",
21 | "Programming Language :: Python :: 3.8",
22 | "Programming Language :: Python :: 3.9",
23 | "Programming Language :: Python :: 3.10",
24 | "Programming Language :: Python :: 3.11",
25 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
26 | "Operating System :: OS Independent",
27 | ],
28 | packages=setuptools.find_packages(),
29 | python_requires=">=3.7",
30 | install_requires=[
31 | "requests>=2.26.0"
32 | ]
33 | )
34 |
--------------------------------------------------------------------------------
/pytion/__init__.py:
--------------------------------------------------------------------------------
1 | import logging
2 | from typing import Optional, Union
3 |
4 | import pytion.envs as envs
5 | from pytion.api import Notion
6 | from pytion.exceptions import *
7 |
8 |
9 | def setup_logging(
10 | level: Union[int, str] = logging.INFO, to_console: bool = True, filename: Optional[str] = None
11 | ) -> None:
12 | """
13 |
14 | :param level: "debug", "info", "warning", "error", "critical" or `logging.INFO` etc.
15 | :param to_console: True/False to output to stdout
16 | :param filename: filename to put logs into file. or None
17 | :return:
18 | """
19 | log_levels = {
20 | "debug": logging.DEBUG,
21 | "info": logging.INFO,
22 | "warning": logging.WARNING,
23 | "error": logging.ERROR,
24 | "critical": logging.CRITICAL,
25 | }
26 | if isinstance(level, str):
27 | if level not in log_levels:
28 | raise ValueError("Invalid log level")
29 | level = log_levels[level]
30 | logger = logging.getLogger(__name__)
31 | logger.handlers.clear()
32 | logger.addHandler(logging.NullHandler())
33 | logger.setLevel(level)
34 | formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
35 | if to_console:
36 | console_handler = logging.StreamHandler()
37 | console_handler.setFormatter(formatter)
38 | logger.addHandler(console_handler)
39 | if filename:
40 | file_handler = logging.FileHandler(filename)
41 | file_handler.setFormatter(formatter)
42 | logger.addHandler(file_handler)
43 |
44 |
45 | setup_logging(level=envs.LOGGING_BASE_LEVEL, to_console=envs.LOGGING_TO_CONSOLE, filename=envs.LOGGING_FILE)
46 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## v1.3.5
4 |
5 | - [#68](https://github.com/lastorel/pytion/issues/68): insert Block support
6 | - [#70](https://github.com/lastorel/pytion/issues/70): fix database filtering using `*_time` attribute
7 | - [#72](https://github.com/lastorel/pytion/issues/72): `public_url` attr added
8 | - [#73](https://github.com/lastorel/pytion/issues/73): Unique ID page property added
9 |
10 | ## v1.3.4
11 |
12 | - [#66](https://github.com/lastorel/pytion/issues/66): full support of `rollup` type properties
13 | - [#55](https://github.com/lastorel/pytion/pull/55): `Optional` typing fix
14 |
15 | ## v1.3.3
16 |
17 | - [#45](https://github.com/lastorel/pytion/issues/45): `has_more` property for relation PropertyValue
18 | - [#47](https://github.com/lastorel/pytion/issues/47): full support of `description` field for Database
19 | - [#46](https://github.com/lastorel/pytion/issues/46): `this_week` filter condition for database query
20 | - `status` type Properties DB filtering added
21 | - [#44](https://github.com/lastorel/pytion/issues/44): `workspace_name` for `bot` type User
22 | - [#43](https://github.com/lastorel/pytion/issues/43): full support of `heading` type blocks
23 |
24 | ## v1.3.2
25 |
26 | - [#34](https://github.com/lastorel/pytion/issues/34): `status` Property type added
27 |
28 | ## v1.3.1
29 |
30 | - [#32](https://github.com/lastorel/pytion/issues/32): Rollback of Page retrieving with properties
31 | - [#35](https://github.com/lastorel/pytion/issues/35): Fix PropertyValue with rollup type
32 |
33 | ## v1.3.0
34 |
35 | - [#27](https://github.com/lastorel/pytion/issues/27): Switched from `2022-02-22` to `2022-06-28` version of Notion API
36 | - `Request()` (internal) method argument added
37 | - [#27](https://github.com/lastorel/pytion/issues/27): Fix of parent object hierarchy
38 | - [#27](https://github.com/lastorel/pytion/issues/27): `models.Block` now has non-empty `parent` attr
39 | - `models.Database`: `is_inline` attr added
40 | - `Notion()`: new optional arg `version` added to customize API interaction
41 | - [#27](https://github.com/lastorel/pytion/issues/27): You must retrieve Page properties manually. `.get_page_properties` method added
42 | - [#27](https://github.com/lastorel/pytion/issues/27): add support of `relation` type `Property`
43 | - [#27](https://github.com/lastorel/pytion/issues/27): updates for `relation` type `PropertyValue`
44 | - [#16](https://github.com/lastorel/pytion/issues/17): tests of Property model
45 | - [#28](https://github.com/lastorel/pytion/issues/28): Add whoami method
46 | - [#16](https://github.com/lastorel/pytion/issues/16): Add search engine
47 |
48 | ### Breaking changes for 1.3.0
49 |
50 | - `Request()` method now looks for positional argument `api` for getting version (internal method)
51 | - Page has title=`unknown` until you retrieve its properties (deprecated statement)
52 | - `PropertyValue` with `relation` type now represents by list of `LinkTo` object instead of list of IDs
--------------------------------------------------------------------------------
/pytion/exceptions.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import logging
4 | import json
5 | from typing import Dict
6 |
7 | from requests import Response
8 |
9 |
10 | logger = logging.getLogger(__name__)
11 |
12 |
13 | class ClientError(Exception):
14 | def __init__(self, message: Response):
15 | req = message
16 | message = f"Failed with code {req.status_code}. Raw: {req.content}"
17 | super(ClientError, self).__init__(message)
18 | self.req = req
19 | self.request_body = req.request.body
20 | self.base = req.url
21 | self.error = message
22 |
23 |
24 | class ServerError(Exception):
25 | def __init__(self, message: Response):
26 | req = message
27 | message = f"Failed with code {req.status_code}. Raw: {req.content}"
28 | super(ServerError, self).__init__(message)
29 | self.req = req
30 | self.request_body = req.request.body
31 | self.base = req.url
32 | self.error = message
33 |
34 |
35 | class InvalidJSON(ClientError):
36 | def __init__(self, req: Response):
37 | message = f"Body could not be decoded as JSON: {req.request.body}"
38 | Exception.__init__(self, message)
39 |
40 |
41 | class InvalidRequestURL(ClientError):
42 | def __init__(self, req: Response):
43 | message = f"The request URL is not valid: {req.url}"
44 | Exception.__init__(self, message)
45 |
46 |
47 | class InvalidRequest(ClientError):
48 | def __init__(self, req: Response):
49 | message = f"This request is not supported: {req.url} {req.request.method}"
50 | Exception.__init__(self, message)
51 |
52 |
53 | class InvalidGrant(ClientError):
54 | def __init__(self, req: Response):
55 | message = (
56 | "The provided authorization grant or refresh token is invalid, expired, revoked, "
57 | "does not match the redirection URI used in the authorization request"
58 | )
59 | Exception.__init__(self, message)
60 |
61 |
62 | class ValidationError(ClientError):
63 | def __init__(self, content: Dict):
64 | message = content.get("message")
65 | message = f"The request body does not match the schema: {message}"
66 | Exception.__init__(self, message)
67 |
68 |
69 | class MissingVersion(ClientError):
70 | def __init__(self, *args):
71 | message = "The request is missing the required Notion-Version header."
72 | Exception.__init__(self, message)
73 |
74 |
75 | class Unauthorized(ClientError):
76 | def __init__(self, *args):
77 | message = "The bearer token is not valid."
78 | Exception.__init__(self, message)
79 |
80 |
81 | class RestrictedResource(ClientError):
82 | def __init__(self, *args):
83 | message = "Given the bearer token used, the client doesn't have permission to perform this operation."
84 | Exception.__init__(self, message)
85 |
86 |
87 | class ObjectNotFound(ClientError):
88 | def __init__(self, req: Response):
89 | message = f"{req.url}" \
90 | "The resource does not exist or the resource has not been shared with owner of the bearer token."
91 | Exception.__init__(self, message)
92 |
93 |
94 | class ConflictError(ClientError):
95 | def __init__(self, *args):
96 | message = "The transaction could not be completed, potentially due to a data collision. Make sure the " \
97 | "parameters are up to date and try again."
98 | Exception.__init__(self, message)
99 |
100 |
101 | class RateLimited(ClientError):
102 | def __init__(self, *args):
103 | message = "This request exceeds the number of requests allowed. Slow down and try again."
104 | Exception.__init__(self, message)
105 |
106 |
107 | class InternalServerError(ServerError):
108 | def __init__(self, req: Response):
109 | self.req = req
110 | self.request_body = req.request.body
111 | self.base = req.url
112 | self.error = req.content
113 | message = f"An unexpected error occurred. Reach out to Notion support. {req.status_code}: " \
114 | f"{req.request.method} {self.base} {self.request_body} -> {self.error}"
115 | Exception.__init__(self, message)
116 |
117 |
118 | class ServiceUnavailable(ServerError):
119 | def __init__(self, *args):
120 | message = "Notion is unavailable. Try again later."
121 | Exception.__init__(self, message)
122 |
123 |
124 | class DatabaseConnectionUnavailable(ServerError):
125 | def __init__(self, *args):
126 | message = "Notion's database is unavailable or in an unqueryable state. Try again later."
127 | Exception.__init__(self, message)
128 |
129 |
130 | class ContentError(Exception):
131 | """Content Exception
132 | If the API URL does not point to a valid Notion API, the server may
133 | return a valid response code, but the content is not json. This
134 | exception is raised in those cases.
135 | """
136 |
137 | def __init__(self, message):
138 | req = message
139 |
140 | message = (
141 | "The server returned invalid (non-json) data. Maybe not a Notion server?"
142 | )
143 |
144 | super(ContentError, self).__init__(message)
145 | self.req = req
146 | self.request_body = req.request.body
147 | self.base = req.url
148 | self.error = message
149 |
150 |
151 | def find_response_error(req: Response) -> Dict:
152 | try:
153 | content = req.json()
154 | except json.JSONDecodeError:
155 | logger.error(f"Result is not OK. JSON decoding fail\n{req.content}")
156 | raise ContentError(req)
157 | if req.ok:
158 | return content
159 | logger.error(f"Result is not OK. {req.status_code}\n{req.reason}")
160 | status_code = int(req.status_code)
161 | error_code = content.get("code")
162 | if error_code:
163 | if error_code == "invalid_json":
164 | raise InvalidJSON(req)
165 | elif error_code == "invalid_request_url":
166 | raise InvalidRequestURL(req)
167 | elif error_code == "invalid_request":
168 | raise InvalidRequest(req)
169 | elif error_code == "invalid_grant":
170 | raise InvalidGrant(req)
171 | elif error_code == "validation_error":
172 | raise ValidationError(content)
173 | elif error_code == "missing_version":
174 | raise MissingVersion()
175 | elif error_code == "unauthorized":
176 | raise Unauthorized()
177 | elif error_code == "restricted_resource":
178 | raise RestrictedResource()
179 | elif error_code == "object_not_found":
180 | raise ObjectNotFound(req)
181 | elif error_code == "conflict_error":
182 | raise ConflictError()
183 | elif error_code == "rate_limited":
184 | raise RateLimited()
185 | elif error_code == "internal_server_error":
186 | raise InternalServerError(req)
187 | elif error_code == "service_unavailable":
188 | raise ServiceUnavailable()
189 | elif error_code == "database_connection_unavailable":
190 | raise DatabaseConnectionUnavailable()
191 | if 400 <= status_code < 500:
192 | raise ClientError(req)
193 | elif 500 <= status_code < 600:
194 | raise ServerError(req)
195 | raise Exception(f"An unexpected error occurred. {req.status_code}: {req.content}")
196 |
--------------------------------------------------------------------------------
/tests/test_query.py:
--------------------------------------------------------------------------------
1 | import requests
2 | import pytest
3 |
4 | import pytion.envs as envs
5 | from pytion import InvalidRequestURL, ContentError, ValidationError, ObjectNotFound
6 | from pytion.query import Sort
7 | from pytion.models import Page
8 |
9 |
10 | class TestRequest:
11 | def test_base(self, no):
12 | assert isinstance(no.session.session, requests.sessions.Session)
13 | assert no.session.session.verify is True
14 | assert no.session.base == envs.NOTION_URL
15 | assert no.session.version == envs.NOTION_VERSION
16 | assert "Notion-Version" in no.session.session.headers
17 |
18 | @pytest.mark.parametrize(
19 | "exec_method,exc",
20 | [
21 | ("post", InvalidRequestURL),
22 | ("PUT", InvalidRequestURL),
23 | ("delete", InvalidRequestURL),
24 | ("bla", ContentError),
25 | ],
26 | )
27 | def test_method__invalid_methods(self, no, exc, exec_method):
28 | with pytest.raises(exc):
29 | no.session.method(exec_method, "pages", id_="878d628488d94894ab14f9b872cd6870")
30 |
31 | def test_method__get(self, no):
32 | # reset cookies after bad requests
33 | no.session.session.cookies.clear()
34 | r = no.session.method("get", "pages", id_="878d628488d94894ab14f9b872cd6870")
35 | assert isinstance(r, dict)
36 | assert len(r) == 13
37 | assert r["object"] == "page"
38 | assert r["archived"] is False
39 | assert r["id"] == "878d6284-88d9-4894-ab14-f9b872cd6870"
40 |
41 | def test_method__patch_empty(self, no):
42 | r = no.session.method("patch", "pages", id_="878d628488d94894ab14f9b872cd6870")
43 | assert isinstance(r, dict)
44 | assert len(r) == 13
45 | assert r["object"] == "page"
46 | assert r["archived"] is False
47 | assert r["id"] == "878d6284-88d9-4894-ab14-f9b872cd6870"
48 |
49 | @pytest.mark.parametrize(
50 | "exec_path,exc",
51 | [
52 | ("page", InvalidRequestURL),
53 | ("DATABASE", InvalidRequestURL),
54 | ("", InvalidRequestURL),
55 | (None, TypeError),
56 | ],
57 | )
58 | def test_method__invalid_endpoints(self, no, exc, exec_path):
59 | with pytest.raises(exc):
60 | no.session.method("get", exec_path, id_="878d628488d94894ab14f9b872cd6870")
61 |
62 | @pytest.mark.parametrize(
63 | "id_,exc",
64 | [
65 | ("878d628488d94894ab14f9b872cd68709", ValidationError),
66 | ("878d6284-88d9-4894-ab14f9b872cd6870", ValidationError),
67 | ("878d628488d94894ab14f9b872cd687a", ObjectNotFound),
68 | ("", InvalidRequestURL),
69 | (None, TypeError),
70 | ],
71 | )
72 | def test_method__invalid_id(self, no, id_, exc):
73 | with pytest.raises(exc):
74 | no.session.method("get", "pages", id_=id_)
75 |
76 | @pytest.mark.parametrize(
77 | "data,exc",
78 | [
79 | ({"archived": False, "paragraph": ""}, ValidationError),
80 | ({"archived": False, "paragraph": {}}, ValidationError),
81 | ({"archived": False, "paragraph": None}, ValidationError),
82 | ({"archived": False, "paragraf": {}}, ValidationError),
83 | ({"archived": False, "synced_block": {}}, ValidationError),
84 | ],
85 | ids=("Empty string", "No rich_text paragraph", "None paragraph", "Wrong attribute name", "Wrong type")
86 | )
87 | def test_method__invalid_data(self, no, data, exc):
88 | block_id = "60c20e13d2ae4ccbb81b5f8f2c532319"
89 | with pytest.raises(exc):
90 | no.session.method("patch", path="blocks", id_=block_id, data=data)
91 |
92 | def test_method__after_path(self, no):
93 | page_id = "82ee5677402f44819a5da3302273400a" # Page with some texts
94 | r = no.session.method("get", path="blocks", id_=page_id, after_path="children")
95 | assert isinstance(r, dict)
96 | assert r["object"] == "list"
97 | assert r["type"] == "block"
98 | assert r["block"] == {}
99 | assert len(r["results"]) == 3
100 |
101 | @pytest.mark.parametrize(
102 | "after_path,exc",
103 | [
104 | ("children", InvalidRequestURL),
105 | ("properties", InvalidRequestURL),
106 | ("None", InvalidRequestURL),
107 | ("query", InvalidRequestURL),
108 | ]
109 | )
110 | def test_method__invalid_after_path(self, no, after_path, exc):
111 | page_id = "82ee5677402f44819a5da3302273400a" # Page with some texts
112 | with pytest.raises(exc):
113 | no.session.method("get", path="pages", id_=page_id, after_path=after_path)
114 |
115 | @pytest.mark.parametrize(
116 | "limit", (1, 10, 100, 101), ids=("1 page", "10 pages", "100 (max) pages", "101 (overmax) pages")
117 | )
118 | def test_method__limit_post(self, no, limit): # no pagination expected
119 | db_id = "7d179e3dbe8e4bf0b605925eee98a194" # Big Database
120 | r = no.session.method("post", path="databases", id_=db_id, after_path="query", data={}, limit=limit)
121 | assert isinstance(r, dict)
122 | assert r["object"] == "list"
123 | assert r["type"] == "page_or_database"
124 | if limit == 101:
125 | assert len(r["results"]) == 100 # no pagination when limit is set
126 | else:
127 | assert len(r["results"]) == limit
128 | assert r["has_more"] is True
129 |
130 | @pytest.mark.parametrize(
131 | "limit", (1, 10, 100, 101), ids=("1 page", "10 pages", "100 (max) pages", "101 (overmax) pages")
132 | )
133 | def test_method__limit_get(self, no, limit):
134 | page_id = "fb40b0c71ed54630ae03cbe12375c4b2"
135 | r = no.session.method("get", path="blocks", id_=page_id, after_path="children", limit=limit)
136 | assert isinstance(r, dict)
137 | assert r["object"] == "list"
138 | assert r["type"] == "block"
139 | if limit == 101:
140 | assert len(r["results"]) == 100 # no pagination when limit is set
141 | else:
142 | assert len(r["results"]) == limit
143 | assert r["has_more"] is True
144 |
145 | def test_method__limit_patch(self, no): # limit in patch mode is ignored
146 | r = no.session.method("patch", "pages", id_="878d628488d94894ab14f9b872cd6870", limit=2)
147 | assert isinstance(r, dict)
148 | assert len(r) == 13
149 | assert r["object"] == "page"
150 | assert r["archived"] is False
151 | assert r["id"] == "878d6284-88d9-4894-ab14-f9b872cd6870"
152 |
153 | def test_method__invalid_limit(self, no):
154 | page_id = "82ee5677402f44819a5da3302273400a" # Page with some texts
155 | with pytest.raises(ValidationError):
156 | no.session.method("get", path="blocks", id_=page_id, after_path="children", limit="query")
157 |
158 | def test_method__paginate(self, no):
159 | db_id = "7d179e3dbe8e4bf0b605925eee98a194" # Big Database
160 | r = no.session.method("post", path="databases", id_=db_id, after_path="query", data={})
161 | assert isinstance(r, dict)
162 | assert r["object"] == "list"
163 | assert r["type"] == "page_or_database"
164 | assert len(r["results"]) == 201
165 | assert r["has_more"] is False
166 | assert r["next_cursor"] is None
167 |
168 |
169 | class TestFilter:
170 | pass
171 |
172 |
173 | class TestSort:
174 | def test_query__ascending(self, little_database):
175 | s = Sort("Digit", "ascending")
176 | r = little_database.db_query(sorts=s)
177 | assert isinstance(r.obj[0], Page)
178 | assert len(r.obj) == 4
179 | assert str(r.obj[0]) == "wait, what?"
180 | assert str(r.obj[1]) == "Parent testing page"
181 | assert "friends" in str(r.obj[2])
182 | assert bool(r.obj[3].title) is False
183 |
184 | def test_query__descending(self, little_database):
185 | s = Sort("Digit", "descending")
186 | r = little_database.db_query(sorts=s)
187 | assert isinstance(r.obj[0], Page)
188 | assert len(r.obj) == 4
189 | assert str(r.obj[2]) == "wait, what?"
190 | assert str(r.obj[1]) == "Parent testing page"
191 | assert "friends" in str(r.obj[0])
192 | assert bool(r.obj[3].title) is False
193 |
194 | def test_query__invalid_direction(self):
195 | with pytest.raises(ValueError):
196 | Sort("Digit", "reverse")
197 |
198 | def test_query__invalid_prop(self, little_database):
199 | s = Sort("Date", "descending")
200 | with pytest.raises(ValidationError):
201 | little_database.db_query(sorts=s)
202 |
203 | def test_query__timestamp(self, little_database):
204 | s = Sort("last_edited_time")
205 | r = little_database.db_query(sorts=s)
206 | assert isinstance(r.obj[0], Page)
207 | assert len(r.obj) == 4
208 | assert str(r.obj[0]) == "We are best friends, body"
209 | assert str(r.obj[2]) == ""
210 | assert "testing" in str(r.obj[1])
211 | assert bool(r.obj[2].title) is False
212 |
--------------------------------------------------------------------------------
/tests/test_models.py:
--------------------------------------------------------------------------------
1 | from pytion.models import *
2 |
3 |
4 | class TestProperty:
5 | def test_create(self):
6 | p = Property.create(type_="multi_select", name="multiselected")
7 | p.get()
8 | assert p.id is None
9 | assert p.type == "multi_select"
10 | assert p.to_delete is False
11 |
12 | def test_create__to_rename(self):
13 | p = Property.create(name="renamed")
14 | p.get()
15 | assert p.id is None
16 | assert p.type == ""
17 | assert p.name == "renamed"
18 | assert p.to_delete is False
19 |
20 | def test_create__to_delete(self):
21 | p = Property.create(type_=None)
22 | p.get()
23 | assert p.id is None
24 | assert p.type is None
25 | assert p.to_delete is True
26 |
27 | def test_create__relation_single(self):
28 | p = Property.create("relation", single_property="878d628488d94894ab14f9b872cd6870")
29 | p.get()
30 | assert p.id is None
31 | assert p.type == "relation"
32 | assert p.to_delete is False
33 | assert isinstance(p.relation, LinkTo)
34 | assert p.relation.uri == "databases"
35 | assert p.subtype == "single_property"
36 |
37 | def test_create__relation_dual(self):
38 | p = Property.create("relation", dual_property="878d628488d94894ab14f9b872cd6870")
39 | p.get()
40 | assert p.id is None
41 | assert p.type == "relation"
42 | assert p.to_delete is False
43 | assert isinstance(p.relation, LinkTo)
44 | assert p.relation.uri == "databases"
45 | assert p.subtype == "dual_property"
46 |
47 | def test_create__status(self):
48 | p = Property.create("status")
49 | p_dict = p.get()
50 | assert p.id is None
51 | assert p.type == "status"
52 | assert p.to_delete is False
53 | assert isinstance(p.options, list)
54 | assert isinstance(p.groups, list)
55 | assert bool(p_dict["status"]) is False
56 |
57 | def test_create__rollup(self):
58 | p = Property.create("rollup", function="average", relation_property_id="GHpm", rollup_property_id="mvpx")
59 | p_dict = p.get()
60 | assert p.id is None
61 | assert p.type == "rollup"
62 | assert p.to_delete is False
63 | assert hasattr(p, "relation_property_name")
64 | assert hasattr(p, "rollup_property_name")
65 | assert p_dict["rollup"]["function"] == "average"
66 | assert p_dict["rollup"]["rollup_property_id"] == "mvpx"
67 | assert "rollup_property_name" not in p_dict
68 |
69 | def test_create__unique_id(self):
70 | p = Property.create("unique_id", prefix="TT")
71 | p_dict = p.get()
72 | assert p.id is None
73 | assert p.type == "unique_id"
74 | assert p.to_delete is False
75 | assert hasattr(p, "prefix")
76 | assert p_dict["unique_id"]["prefix"] == "TT"
77 |
78 |
79 | class TestPropertyFull:
80 | def test_create__rollup_id(self, database_for_updates, database_for_pages):
81 | assert "Relation 1" in database_for_updates.obj.properties
82 | assert "Rollup 2" not in database_for_updates.obj.properties
83 | relation_id = database_for_updates.obj.properties["Relation 1"].id
84 | rollup_id = database_for_pages.obj.properties["when"].id
85 | function = "earliest_date"
86 | properties = {
87 | "Rollup 2": Property.create(
88 | "rollup", function=function,
89 | relation_property_id=relation_id, rollup_property_id=rollup_id
90 | )
91 | }
92 | database = database_for_updates.db_update(properties=properties)
93 | assert "Rollup 2" in database.obj.properties
94 | assert database.obj.properties["Rollup 2"].type == "rollup"
95 |
96 | properties["Rollup 2"] = Property.create(None)
97 | database = database.db_update(properties=properties)
98 | assert "Rollup 2" not in database.obj.properties
99 |
100 | def test_create__rollup_name(self, database_for_updates):
101 | assert "Relation 1" in database_for_updates.obj.properties
102 | assert "Rollup 2" not in database_for_updates.obj.properties
103 | relation_name = "Relation 1"
104 | rollup_name = "when"
105 | function = "unique"
106 | properties = {
107 | "Rollup 2": Property.create(
108 | "rollup", function=function,
109 | relation_property_name=relation_name, rollup_property_name=rollup_name
110 | )
111 | }
112 | database = database_for_updates.db_update(properties=properties)
113 | assert "Rollup 2" in database.obj.properties
114 | assert database.obj.properties["Rollup 2"].type == "rollup"
115 |
116 | properties["Rollup 2"] = Property.create(None)
117 | database = database.db_update(properties=properties)
118 | assert "Rollup 2" not in database.obj.properties
119 |
120 | def test_change__rollup(self, database_for_updates):
121 | assert "Rollup 1" in database_for_updates.obj.properties
122 | old_function = database_for_updates.obj.properties["Rollup 1"].function
123 | old_relation_id = database_for_updates.obj.properties["Rollup 1"].relation_property_id
124 | old_rollup_id = database_for_updates.obj.properties["Rollup 1"].rollup_property_id
125 | new_function = "not_empty"
126 | new_relation_name = "Relation 2"
127 | new_rollup_name = "Tags"
128 | properties = {
129 | "Rollup 1": Property.create(
130 | "rollup", function=new_function,
131 | relation_property_name=new_relation_name, rollup_property_name=new_rollup_name
132 | )
133 | }
134 | database = database_for_updates.db_update(properties=properties)
135 | assert database.obj.properties["Rollup 1"].function == new_function
136 | assert database.obj.properties["Rollup 1"].relation_property_name == "Relation 2"
137 | assert database.obj.properties["Rollup 1"].rollup_property_name == new_rollup_name
138 | # revert
139 | properties = {
140 | "Rollup 1": Property.create(
141 | "rollup", function=old_function,
142 | relation_property_id=old_relation_id, rollup_property_id=old_rollup_id
143 | )
144 | }
145 | database = database.db_update(properties=properties)
146 | assert database.obj.properties["Rollup 1"].function == old_function
147 | assert database.obj.properties["Rollup 1"].rollup_property_id == old_rollup_id
148 |
149 | def test_create__unique_id(self):
150 | # don't test creating unique_id property.
151 | # on second iteration it breaks the database (error 500)
152 | pass
153 |
154 |
155 | class TestPropertyValue:
156 | def test_create__status(self):
157 | pv = PropertyValue.create("status", value="Done")
158 | p_dict = pv.get()
159 | assert pv.id is None
160 | assert pv.type == "status"
161 | assert p_dict["status"]["name"] == "Done"
162 |
163 | def test_create__relation(self):
164 | pv = PropertyValue.create("relation", value=[LinkTo.create(page_id="04262843082a478d97f741948a32613c")])
165 | p_dict = pv.get()
166 | assert pv.id is None
167 | assert pv.type == "relation"
168 | assert pv.has_more is False
169 | assert p_dict["relation"][0]["id"] == "04262843082a478d97f741948a32613c"
170 |
171 |
172 | class TestPropertyValueFull:
173 | def test_read__unique_id(self, no, little_database):
174 | page = no.pages.get("b85877eaf7bf4245a8c5218055eeb81f")
175 | assert "uID" in little_database.obj.properties
176 | assert little_database.obj.properties["uID"].prefix == "LD"
177 | assert page.obj.properties["uID"].value == 3
178 |
179 |
180 | class TestBlock:
181 | def test_get__heading_1(self, no):
182 | block_id = "15a5790980db4e8798b9b7801385afbb"
183 | block = no.blocks.get(block_id)
184 | assert isinstance(block.obj, Block)
185 | assert isinstance(block.obj.text, RichTextArray)
186 | assert block.obj.type == "heading_1"
187 | assert block.obj.simple == "Block with heading 1 type"
188 | assert str(block.obj) == "# Block with heading 1 type"
189 | assert block.obj.has_children is False
190 | assert block.obj.is_toggleable is False
191 |
192 | def test_get__t_heading_1(self, no):
193 | block_id = "a62985febcac499f95e5b59643df6180"
194 | block = no.blocks.get(block_id)
195 | assert isinstance(block.obj, Block)
196 | assert isinstance(block.obj.text, RichTextArray)
197 | assert block.obj.type == "heading_1"
198 | assert block.obj.simple == "Block with Toggle Heading 1 type with no children"
199 | assert str(block.obj) == "# Block with Toggle Heading 1 type with no children"
200 | assert block.obj.has_children is False
201 | assert block.obj.is_toggleable is True
202 |
203 | def test_get__t_heading_2(self, no):
204 | block_id = "4b265c74e7644affad13a3820e208b78"
205 | block = no.blocks.get(block_id)
206 | assert isinstance(block.obj, Block)
207 | assert isinstance(block.obj.text, RichTextArray)
208 | assert block.obj.type == "heading_2"
209 | assert block.obj.simple == "Block with Toggle Heading 2 type with children"
210 | assert str(block.obj) == "## Block with Toggle Heading 2 type with children"
211 | assert block.obj.has_children is True
212 | assert block.obj.is_toggleable is True
213 |
214 | def test_create__heading_1(self):
215 | b = Block.create("hello there", type_="heading_1")
216 | b_dict = b.get()
217 | assert b.id == ""
218 | assert b.type == "heading_1"
219 | assert b_dict["heading_1"]["is_toggleable"] is False
220 |
221 | def test_create__t_heading_2(self):
222 | b = Block.create("hello there", type_="heading_2", is_toggleable=True)
223 | b_dict = b.get()
224 | assert b.id == ""
225 | assert b.type == "heading_2"
226 | assert b_dict["heading_2"]["is_toggleable"] is True
227 |
--------------------------------------------------------------------------------
/pytion/query.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | import logging
4 | from urllib.parse import urlencode
5 | from typing import Dict, Optional, Any, Union
6 | from datetime import datetime
7 |
8 | import requests
9 |
10 | import pytion.envs as envs
11 | from pytion.models import Property, PropertyValue, User
12 | from pytion.exceptions import find_response_error
13 |
14 |
15 | logger = logging.getLogger(__name__)
16 |
17 |
18 | class Filter(object):
19 | _filter_condition_types = [
20 | "rich_text", "number", "checkbox", "select", "multi_select", "date", "phone_number", "people", "title",
21 | "created_time", "last_edited_time", "phone_number", "status", "timestamp"
22 | ]
23 |
24 | def __init__(
25 | self,
26 | property_name: Optional[str] = None,
27 | value: Optional[Any] = None,
28 | property_type: Optional[str] = None,
29 | condition: Optional[str] = None,
30 | raw: Optional[Dict] = None,
31 | property_obj: Optional[Union[Property, PropertyValue]] = None,
32 | **kwargs,
33 | ):
34 | if raw:
35 | self.filter = raw
36 | return
37 | if property_obj:
38 | if property_obj.id:
39 | self.property_name = property_obj.id
40 | else:
41 | self.property_name = property_obj.name
42 | if property_obj.type in ["title", "rich_text", "url", "email"]:
43 | self.property_type = "rich_text"
44 | elif "time" in property_obj.type:
45 | self.property_type = "date"
46 | else:
47 | self.property_type = property_obj.type
48 | else:
49 | self.property_type = property_type
50 | self.property_name = property_name
51 |
52 | if self.property_type not in self._filter_condition_types:
53 | raise ValueError(f"Allowed types {self.allowed_condition_types} ({property_type} provided)")
54 |
55 | if self.property_type == "rich_text":
56 | self.condition = "contains" if not condition else condition
57 | self.value = str(value)
58 | elif self.property_type == "number":
59 | self.condition = "equals" if not condition else condition
60 | if "." in value:
61 | self.value = float(value)
62 | else:
63 | self.value = int(value)
64 | elif self.property_type == "checkbox":
65 | self.condition = "equals" if not condition else condition
66 | self.value = bool(value) if value else True
67 | elif self.property_type == "select":
68 | self.condition = "equals" if not condition else condition
69 | self.value = str(value)
70 | elif self.property_type == "multi_select":
71 | self.condition = "contains" if not condition else condition
72 | self.value = value[0] if isinstance(value, list) else str(value)
73 | elif self.property_type == "phone_number":
74 | self.condition = "contains" if not condition else condition
75 | self.value = str(value)
76 | elif self.property_type == "people":
77 | self.condition = "contains" if not condition else condition
78 | if isinstance(value, User):
79 | self.value = value.id
80 | else:
81 | self.value = str(value)
82 | elif self.property_type == "title":
83 | self.condition = "contains" if not condition else condition
84 | self.value = str(value)
85 | elif self.property_type == "date" or "_time" in self.property_type or self.property_type == "timestamp":
86 | self.condition = "equals" if not condition else condition
87 | if isinstance(value, datetime):
88 | if not value.hour and not value.minute:
89 | self.value = str(value.date())
90 | else:
91 | self.value = value.isoformat()
92 | else:
93 | self.value = str(value)
94 | elif self.property_type == "status":
95 | self.condition = "equals" if not condition else condition
96 | self.value = str(value)
97 |
98 | if property_obj and not value:
99 | self.value = getattr(property_obj, "value", None)
100 | if isinstance(self.value, list):
101 | self.value = self.value[0]
102 | if self.condition in ["is_empty", "is_not_empty"]:
103 | self.value = True
104 | elif self.condition in [
105 | "past_week", "past_month", "past_year", "next_week", "next_month", "next_year", "this_week"
106 | ]:
107 | self.value = {}
108 | self.filter = {
109 | "property": self.property_name,
110 | self.property_type: {self.condition: self.value}
111 | }
112 | # #70
113 | if "_time" in self.property_type:
114 | del self.filter["property"]
115 | self.filter["timestamp"] = self.property_type
116 | if self.property_type == "timestamp":
117 | del self.filter["property"]
118 | self.filter["timestamp"] = self.property_name # created_time or last_edited_time
119 | self.filter[self.property_name] = {self.condition: self.value}
120 |
121 | @property
122 | def allowed_condition_types(self):
123 | return ", ".join(self._filter_condition_types)
124 |
125 | def __repr__(self):
126 | if not getattr(self, "property_type"):
127 | return f"Filter({str(self.filter)})"
128 | return f"Filter({self.property_name} {self.condition} {self.value})"
129 |
130 |
131 | class Sort(object):
132 | directions = ["ascending", "descending"]
133 |
134 | def __init__(self, property_name: str, direction: str = "ascending"):
135 | """
136 | Sort object is used while querying database or search query:
137 | - self.sort object is used in search query (only single item supported by API)
138 | - self.sorts can contain multiple criteria and is used in database query
139 | """
140 | if direction not in self.directions:
141 | raise ValueError(f"Allowed types {self.directions} ({direction} is provided)")
142 | if property_name in ("created_time", "last_edited_time"):
143 | self.sort = {"timestamp": property_name, "direction": direction}
144 | self.sorts = [self.sort]
145 | else:
146 | self.sort = {"property": property_name, "direction": direction}
147 | self.sorts = [self.sort]
148 |
149 | def add(self, property_name: str, direction: str):
150 | if direction not in self.directions:
151 | raise ValueError(f"Allowed types {self.directions} ({direction} is provided)")
152 | self.sort = {"property": property_name, "direction": direction}
153 | self.sorts.append(self.sort)
154 |
155 | def __repr__(self):
156 | r = [e.values() for e in self.sorts]
157 | return f"Sorts({r})"
158 |
159 |
160 | class Request(object):
161 | def __init__(
162 | self,
163 | api: object, # Notion object
164 | method: Optional[str] = None,
165 | path: Optional[str] = None,
166 | id_: str = "",
167 | data: Optional[Dict] = None,
168 | base: Optional[str] = None,
169 | token: Optional[str] = None,
170 | after_path: Optional[str] = None,
171 | limit: int = 0,
172 | filter_: Optional[Filter] = None,
173 | sorts: Optional[Sort] = None,
174 | ):
175 | self.session = requests.Session()
176 | self.session.headers["accept"] = "application/json"
177 | self.base = base if base else envs.NOTION_URL
178 | self._token = token if token else envs.NOTION_SECRET
179 | if not self._token:
180 | logger.error("Token is not provided or file `token` is not found!")
181 | self.version = getattr(api, "version")
182 | self.auth = {"Authorization": "Bearer " + self._token}
183 | self.session.headers.update({"Notion-Version": self.version, **self.auth})
184 | self.result = None
185 |
186 | if method:
187 | self.result = self.method(method, path, id_, data, after_path, limit, filter_, sorts)
188 |
189 | def method(
190 | self, method: str, path: str, id_: str = "", data: Optional[Dict] = None,
191 | after_path: Optional[str] = None, limit: int = 0, filter_: Optional[Filter] = None,
192 | sorts: Optional[Sort] = None, pagination_loop: bool = False, sort: Optional[Sort] = None,
193 | ):
194 | if filter_:
195 | if data:
196 | data["filter"] = filter_.filter
197 | else:
198 | data = {"filter": filter_.filter}
199 | if sorts:
200 | if data:
201 | data["sorts"] = sorts.sorts
202 | else:
203 | data = {"sorts": sorts.sorts}
204 | if sort: # specific attr in 'search' query. strange
205 | if data:
206 | data["sort"] = sort.sort
207 | else:
208 | data = {"sort": sort.sort}
209 | url = self.base + path + "/" + id_
210 | if limit and method == "get":
211 | if after_path:
212 | after_path += "?" + urlencode({"page_size": limit})
213 | else:
214 | path += "?" + urlencode({"page_size": limit})
215 | if limit and method == "post":
216 | if not data:
217 | data = {}
218 | data.update({"page_size": limit})
219 | if after_path:
220 | url += "/" + after_path
221 | logger.info(f"Request {method} {url}")
222 | logger.debug(f"METHOD: {method.upper()}")
223 | logger.debug(f"URL: {url}")
224 | logger.debug(f"DATA: {data}")
225 | result = self.session.request(method=method, url=url, json=data)
226 | logger.debug(f"STATUS CODE: {result.status_code}")
227 | logger.debug(f"CONTENT: {result.content}")
228 | logger.info(f"{result.status_code} Received")
229 |
230 | r = find_response_error(result)
231 |
232 | # pagination section
233 | if not limit and not pagination_loop:
234 | self.paginate(r, method, path, id_, data, after_path)
235 |
236 | return r
237 |
238 | def paginate(self, result, method, path, id_, data, after_path):
239 | if (result.get("has_more", False) is True) and (result.get("object", "") == "list"):
240 | next_start = result.get("next_cursor")
241 | logger.info(f"Paginated answer. Repeat with offset {next_start}")
242 |
243 | super_after_path = after_path
244 | super_path = path
245 |
246 | while next_start:
247 | # if GET method then parameters are in request string
248 | # if POST method then parameters are in body
249 | if method == "get":
250 | if after_path:
251 | super_after_path = after_path + "?" + urlencode({"start_cursor": next_start})
252 | else:
253 | super_path = path + "?" + urlencode({"start_cursor": next_start})
254 | elif method == "post":
255 | if not data:
256 | data = {}
257 | data.update({"start_cursor": next_start})
258 |
259 | r = self.method(method, super_path, id_, data, super_after_path, pagination_loop=True)
260 | if r.get("object", "") == "list" and r.get("results"):
261 | result["results"].extend(r["results"])
262 | if r.get("has_more"):
263 | next_start = r.get("next_cursor")
264 | else:
265 | next_start = None
266 | result["has_more"] = r.get("has_more")
267 | result["next_cursor"] = r.get("next_cursor")
268 |
--------------------------------------------------------------------------------
/pytion/api.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import annotations
3 |
4 | import logging
5 | from typing import Optional, Union, Dict, List
6 |
7 | import pytion.envs as envs
8 | from pytion.query import Request, Filter, Sort
9 | from pytion.models import Database, Page, Block, BlockArray, PropertyValue, PageArray, LinkTo, RichTextArray, Property
10 | from pytion.models import ElementArray, User
11 |
12 |
13 | Models = Union[Database, Page, Block, BlockArray, PropertyValue, PageArray, ElementArray]
14 | logger = logging.getLogger(__name__)
15 |
16 |
17 | class Notion(object):
18 | def __init__(self, token: Optional[str] = None, version: Optional[str] = None):
19 | """
20 | Creates main API object.
21 |
22 | :param token: provide your integration API token. If None - find the file `token`
23 | :param version: provide non hardcoded API version
24 | """
25 | self.version = version if version else envs.NOTION_VERSION
26 | self.session = Request(api=self, token=token)
27 | logger.debug(f"API object created. Version {envs.NOTION_VERSION}")
28 |
29 | def search(
30 | self, query: Optional[str] = None, limit: int = 0,
31 | object_type: Optional[str] = None, sort_last_edited_time: Optional[str] = None
32 | ) -> Optional[Element]:
33 | """
34 | Searches all original pages, databases, and child pages/databases that are shared with the integration.
35 | It will not return linked databases, since these duplicate their source databases. (c)
36 |
37 |
38 | :param query: search by page title
39 | :param limit: 0 < int < 100 - max number of items to be returned (0 = return all)
40 | :param object_type: filter by type: 'page' or 'database'
41 | :param sort_last_edited_time: sorting 'ascending' or 'descending'
42 | :return:
43 |
44 | `r = no.search("pytion", 10, sort_last_edited_time="ascending")`
45 | `print(r.obj)`
46 | """
47 | data = {"query": query} if query else None
48 | filter_ = Filter(raw={"property": "object", "value": object_type}) if object_type else None
49 | if sort_last_edited_time:
50 | sort_last_edited_time = Sort(property_name="last_edited_time", direction=sort_last_edited_time)
51 | result = self.session.method(
52 | "post", "search", sort=sort_last_edited_time, filter_=filter_, limit=limit, data=data
53 | )
54 | if "results" in result and isinstance(result["results"], list):
55 | data = ElementArray(result["results"])
56 | for item in data:
57 | if isinstance(item, Page):
58 | self.pages.get_page_properties(title_only=True, obj=item)
59 | return Element(api=self, name="search", obj=data)
60 | else:
61 | logger.warning("Results list is not found")
62 | return None
63 |
64 | def __len__(self):
65 | return 1
66 |
67 | def __repr__(self):
68 | return "NotionAPI"
69 |
70 | def __str__(self):
71 | return self.__repr__()
72 |
73 | def __getattr__(self, name):
74 | if name in dir(self):
75 | return self.name
76 | return Element(self, name)
77 |
78 |
79 | class Element(object):
80 | class_map = {"page": Page, "database": Database, "block": Block, "user": User}
81 |
82 | def __init__(self, api: Notion, name: str, obj: Optional[Models] = None):
83 | self.api = api
84 | self.name = name
85 | self.obj = obj
86 | logger.debug(f"Element {self!r} created")
87 |
88 | def get(self, id_: str, _after_path: str = None, limit: int = 0) -> Element:
89 | """
90 | Get Element by ID.
91 | .exceptions.ObjectNotFound exception if not found
92 |
93 | :return: `Element.obj` may be `Page`, `Database`, `Block`
94 |
95 | result = no.databases.get("1234123412341")
96 | result = no.pages.get("123412341234")
97 | result = no.blocks.get("123412341234")
98 | result = no.users.get("123412341234")
99 | print(result.obj)
100 | """
101 | if "-" in id_:
102 | id_ = id_.replace("-", "")
103 | if not _after_path:
104 | raw_obj = self.api.session.method(method="get", path=self.name, id_=id_, limit=limit)
105 | else:
106 | raw_obj = self.api.session.method(
107 | method="get", path=self.name, id_=id_, after_path=_after_path, limit=limit
108 | )
109 | if raw_obj["object"] == "list":
110 | if self.name == "pages":
111 | self.obj = PageArray(raw_obj["results"])
112 | elif self.name == "blocks":
113 | self.obj = BlockArray(raw_obj["results"])
114 | else:
115 | self.obj = ElementArray(raw_obj["results"])
116 | else:
117 | self.obj = self.class_map[raw_obj["object"]](**raw_obj)
118 | return self
119 |
120 | def get_parent(self, id_: Optional[str] = None) -> Optional[Element]:
121 | """
122 | Get parent object of current object if possible.
123 |
124 | :param id_:
125 | :return: Element (parent object) or None. `.obj` may be `Page`, `Database`, `Block`
126 |
127 | `result = no.blocks.get_parent("123412341234")`
128 | `print(result)`
129 | Notion/pages/Page(Page Title here)
130 | `result = result.get_parent()`
131 | `print(result)`
132 | Notion/databases/Database(Some database name)
133 | """
134 | if not self.obj:
135 | self.get(id_)
136 | if getattr(self.obj, "parent", None):
137 | return self.from_linkto(self.obj.parent)
138 | logger.warning(f"Parent object can not be found")
139 | return None
140 |
141 | def get_block_children(
142 | self, id_: Optional[str] = None, block: Optional[Block] = None, limit: int = 0
143 | ) -> Optional[Element]:
144 | """
145 | Get children Block objects of current Block object (tabulated texts) if exist (else None)
146 |
147 | :param id_:
148 | :param block: you can provide a Block object instead to get his children
149 | :param limit: 0 < int < 100 - max number of items to be returned (0 = return all)
150 | :return: `Element.obj` will be BlockArray object even nothing is found
151 |
152 | `print(no.pages.get_block_children("PAGE ID"))`
153 | None
154 |
155 | `print(no.blocks.get_block_children("PAGE ID"))`
156 | Notion/blocks/BlockArray(Heading 2 level Paragraph some)
157 |
158 | `print(no.blocks.get_block_children("PAGE ID").obj)`
159 | Heading 2 level
160 | Paragraph
161 | some text
162 |
163 | BlockArray or Database object expected.
164 | """
165 | if self.name not in ("blocks", "pages"):
166 | logger.warning("Only `blocks` or `pages` can have children")
167 | return None
168 | if isinstance(id_, str) and "-" in id_:
169 | id_ = id_.replace("-", "")
170 | obj = block if block else self.obj
171 | if obj:
172 | return self.from_linkto(obj.children, limit=limit)
173 | child = self.api.session.method(
174 | method="get", path="blocks", id_=id_, after_path="children", limit=limit
175 | )
176 | # children object returns list of Blocks
177 | if child["object"] != "list":
178 | logger.warning(f"List of Blocks expected. Received\n{child}")
179 | return None
180 | return Element(api=self.api, name="blocks", obj=BlockArray(child["results"]))
181 |
182 | def get_block_children_recursive(
183 | self, id_: Optional[str] = None, max_depth: int = 10, block: Optional[Block] = None,
184 | _cur_depth: int = 0, limit: int = 0, force: bool = False
185 | ) -> Optional[Element]:
186 | """
187 | Get children Block objects of current Block object (tabulated texts) if exist (else None) recursive
188 |
189 | :param id_:
190 | :param block: you can provide a Block object instead to get his children
191 | :param max_depth: how deep use the recursion (block inside block inside block etc.)
192 | :param limit: 0 < int < 100 - max number of items to be returned (0 = return all)
193 | :param force: get blocks in subpages too
194 | :return: `Element.obj` will be BlockArray object even nothing is found
195 |
196 | `print(no.blocks.get_block_children_recursive("PAGE ID").obj)`
197 | Heading 2 level
198 | Paragraph
199 | block inside block
200 | some text
201 | """
202 | if self.name not in ("blocks", "pages"):
203 | logger.warning("Only `blocks` or `pages` can have children")
204 | return None
205 | if isinstance(id_, str) and "-" in id_:
206 | id_ = id_.replace("-", "")
207 | obj = block if block else self.obj
208 | if obj:
209 | id_ = obj.id
210 | if isinstance(obj, Block) and obj.type == "child_database":
211 | return self.from_linkto(obj.children)
212 | child = self.api.session.method(
213 | method="get", path="blocks", id_=id_, after_path="children", limit=limit
214 | )
215 | ba = BlockArray([])
216 | for b in child["results"]:
217 | block_obj = Block(level=_cur_depth, **b)
218 | ba.append(block_obj)
219 | # Do not get subpages if not force
220 | if block_obj.type == "child_page" and not force:
221 | continue
222 | if block_obj.has_children and _cur_depth < max_depth:
223 | sub_element = Element(api=self.api, name="blocks").get_block_children_recursive(
224 | id_=block_obj.id, max_depth=max_depth, _cur_depth=_cur_depth + 1, limit=limit, force=force
225 | )
226 | ba.extend(sub_element.obj)
227 |
228 | return Element(api=self.api, name="blocks", obj=ba)
229 |
230 | def get_page_property(self, property_id: str, id_: Optional[str] = None, limit: int = 0) -> Optional[Element]:
231 | """
232 | DEPRECATED
233 | Retrieve a page property item.
234 |
235 | :param property_id: ID of property in current database
236 | :param id_: ID of page in that database (if not `self.obj`)
237 | :param limit: 0 < int < 100 - max number of items to be returned (0 = return all)
238 | :return: `Element.obj` will be PropertyValue object
239 |
240 | `db = no.databases.get("1232412341234")`
241 | `property_id = db.obj.properties["Last edited time"].id`
242 | `result = no.pages.get_page_property(property_id, 'PAGE ID 152f123a12344')`
243 | `print(result.obj)`
244 | 2021-11-04 16:47:00+00:00
245 | """
246 | if self.name != "pages":
247 | logger.warning("Only `pages` can have properties")
248 | return None
249 | if isinstance(id_, str) and "-" in id_:
250 | id_ = id_.replace("-", "")
251 | if self.obj and not id_:
252 | id_ = self.obj.id
253 | property_obj = self.api.session.method(
254 | method="get", path=self.name, id_=id_, after_path="properties/"+property_id, limit=limit
255 | )
256 | return Element(api=self.api, name=f"pages/{id_}/properties", obj=PropertyValue(property_obj, property_id))
257 |
258 | def get_page_properties(self, title_only: bool = False, obj: Optional[Page] = None) -> None:
259 | """
260 | Page properties must be retrieved using the page properties endpoint. (c)
261 | after retrieving a Page object you can retrieve its properties
262 |
263 | obj or self.obj must be a Page
264 | :return:
265 | """
266 | if not obj:
267 | obj = self.obj
268 | if obj and isinstance(obj, Page):
269 | for prop in obj.properties:
270 | # Skip already retrieved properties
271 | if isinstance(obj.properties[prop], PropertyValue):
272 | continue
273 | prop_id = obj.properties[prop].id
274 | if title_only and prop_id != "title":
275 | continue
276 | result = self.get_page_property(prop_id, id_=obj.id)
277 | obj.properties[prop] = result.obj
278 | if prop_id == "title":
279 | obj.title = result.obj.value if result.obj.value else ""
280 | return
281 | logger.warning("You must provide a Page to retrieve properties")
282 |
283 | def db_query(
284 | self,
285 | id_: Optional[str] = None,
286 | limit: int = 0,
287 | filter_: Optional[Filter] = None,
288 | sorts: Optional[Sort] = None,
289 | **kwargs,
290 | ) -> Optional[Element]:
291 | if self.name != "databases":
292 | logger.warning("Only `databases` can be queried")
293 | return None
294 | if isinstance(id_, str) and "-" in id_:
295 | id_ = id_.replace("-", "")
296 | if self.obj:
297 | id_ = self.obj.id
298 | r = self.api.session.method(
299 | method="post", path=self.name, id_=id_, after_path="query",
300 | data={}, limit=limit, filter_=filter_, sorts=sorts
301 | )
302 | if r["object"] != "list":
303 | return None
304 | return Element(api=self.api, name="pages", obj=PageArray(r["results"]))
305 |
306 | def db_filter(self, title: str = None, **kwargs) -> Optional[Element]:
307 | """
308 | :param title: filter by title contains + opt. attrs: condition, sort etc.
309 | OR
310 | :param property_name: mandatory - full name or ID of property to filter by
311 | :param value: the value of this property to filter by (may be bool or datetime etc.)
312 | :param property_type: mandatory field - `text`, `number`, `checkbox`, `date`, `select` etc.
313 | :param condition: optional field - it depends on the type: `starts_with`, `contains`, `equals` etc.
314 | :param raw: correctly formatted dict to pass direct to API (instead of all other params)
315 | :param property_obj: Property or PropertyValue obj. instead of `property_name` and `property_type`,
316 | PropertyValue can put value in request, if `value` is not provided
317 |
318 | :param ascending: property name to be sorted by
319 | :param descending: property name to be sorted by
320 |
321 | :param limit: 0 < int < 100 - max number of items to be returned (0 = return all)
322 | :return: self.obj -> PageArray
323 |
324 | examples
325 | `.db_filter("My Page Title")`
326 | `.db_filter("", ascending="Tags")`
327 | `.db_filter(property_name="Done", property_type="checkbox")`
328 | `.db_filter(property_name="Done", property_type="checkbox", value=False, descending="title")`
329 | `.db_filter(property_name="tags", property_type="multi_select", condition="is_not_empty")`
330 | `.db_filter(property_name="created_time", property_type="timestamp", condition="before", value=datetime.now())`
331 | `.db_filter(raw=YOUR_BIG_DICT_FROM_NOTION_DOCS, limit=2)`
332 |
333 | Filters combinations are not supported. (in `raw` param only)
334 | """
335 | if self.name == "databases" and self.obj:
336 | sort = None
337 | if kwargs.get("ascending"):
338 | sort = Sort(property_name=kwargs["ascending"], direction="ascending")
339 | elif kwargs.get("descending"):
340 | sort = Sort(property_name=kwargs["descending"], direction="descending")
341 | if isinstance(title, str):
342 | filter_obj = Filter(property_name="title", value=title, property_type="title", **kwargs)
343 | else:
344 | filter_obj = Filter(**kwargs)
345 | return self.db_query(filter_=filter_obj, sorts=sort, **kwargs)
346 | logger.warning("Database must be provided. use .get() before")
347 | return None
348 |
349 | def db_create(
350 | self,
351 | database_obj: Optional[Database] = None,
352 | parent: Optional[LinkTo] = None,
353 | properties: Optional[Dict[str, Property]] = None,
354 | title: Optional[Union[str, RichTextArray]] = None,
355 | description: Optional[Union[str, RichTextArray]] = None,
356 | ) -> Optional[Element]:
357 | """
358 | :param database_obj: you can provide `Database` object or -
359 | provide the params for creating it:
360 | :param parent: parent object in LinkTo format. workspace can not be a parent
361 | :param properties: dict of properties. Property with `title` type is mandatory!
362 | :param title: your name of the Database
363 | :param description: optional description for new Database
364 | :return: self.obj -> Database
365 |
366 | `parent = LinkTo.create(database_id="24512345125123421")`
367 | `p1 = Property.create(name="renamed")`
368 | `p2 = Property.create(type_="multi_select", name="multiselected")`
369 | `props = {"Property1_name": p1, "Property2_name": p2}` OR
370 | ```props = {
371 | "Name": Property.create("title")
372 | "Digit": Property.create("number"),
373 | "Status": Property.create("select")
374 | }```
375 | `db = db.db_create(parent=parent, properties=props, title=RichTextArray.create("NEW DB"))`
376 | """
377 | if self.name != "databases":
378 | logger.warning("Method supports `databases` only")
379 | return None
380 | if database_obj:
381 | db = database_obj
382 | else:
383 | if isinstance(title, str):
384 | title = RichTextArray.create(title)
385 | db = Database.create(parent=parent, properties=properties, title=title, description=description)
386 | created_db = self.api.session.method(method="post", path=self.name, data=db.get())
387 | self.obj = Database(**created_db)
388 | return self
389 |
390 | def db_update(
391 | self, id_: Optional[str] = None, title: Optional[Union[str, RichTextArray]] = None,
392 | properties: Optional[Dict[str, Property]] = None
393 | ) -> Optional[Element]:
394 | """
395 | :param id_: provide id of database if `self.obj` is empty
396 | :param title: provide RichTextArray or text to rename database
397 | :param properties: provide dict of Property to update them
398 | :return: self.obj -> Database
399 |
400 |
401 | `rename_prop = Property.create(name="renamed")`
402 | `rename_retype_prop = Property.create(type_="multi_select", name="multiselected")`
403 | `retype_prop = Property.create("checkbox")`
404 | `props = {"Property1_name": rename_retype_prop, "Property2_ID": retype_prop}`
405 | `db = db.db_update(properties=props, title=RichTextArray.create("NEW DB"))`
406 | """
407 | if self.name != "databases":
408 | logger.warning("Method supports `databases` only")
409 | return None
410 | if isinstance(id_, str) and "-" in id_:
411 | id_ = id_.replace("-", "")
412 | if self.obj:
413 | id_ = self.obj.id
414 | patch = {}
415 | if title:
416 | if isinstance(title, str):
417 | title = RichTextArray.create(title)
418 | patch["title"] = title.get()
419 | if properties:
420 | patch["properties"] = {name: value.get() for name, value in properties.items()}
421 | updated_db = self.api.session.method(method="patch", path=self.name, id_=id_, data=patch)
422 | self.obj = Database(**updated_db)
423 | return self
424 |
425 | def page_create(
426 | self,
427 | page_obj: Optional[Page] = None,
428 | parent: Optional[LinkTo] = None,
429 | properties: Optional[Dict[str, PropertyValue]] = None,
430 | title: Optional[Union[str, RichTextArray]] = None,
431 | children: Union[BlockArray, List[Block], None] = None,
432 | ) -> Optional[Element]:
433 | """
434 | :param page_obj: you can provide `Page` object or -
435 | provide the params for creating it:
436 | :param parent: LinkTo object with ID of parent element. workspace can not be a parent
437 | :param properties: Dict of properties with values
438 | :param title: New title
439 | :param children: Content of new page in [Block] or BlockArray format
440 | :return: self.obj -> Page
441 |
442 | `parent = LinkTo.create(database_id="24512345125123421")`
443 | `p2 = PropertyValue.create("date", datetime.now())`
444 | `r = no.pages.page_create(parent=parent, properties={"Count": p1, "Date": p2}, title="Extra PAGE")`
445 |
446 | `props["Status"] = PropertyValue.create("select", "new select option")`
447 | `props["Tags"] = PropertyValue.create("multi_select", ["new-option1", "new option2"])`
448 | `no.pages.create(parent=parent, properties=props)`
449 |
450 | `parent2 = LinkTo.create(page_id="123412341234")`
451 | `no.pages.page_create(parent=parent2, title="New page 121")`
452 | """
453 | if self.name != "pages":
454 | logger.warning("Method supports `pages` only")
455 | return None
456 | if page_obj:
457 | page = page_obj
458 | else:
459 | if children and not isinstance(children, BlockArray):
460 | children = BlockArray(children, create=True)
461 | page = Page.create(parent=parent, properties=properties, title=title, children=children)
462 | created_page = self.api.session.method(method="post", path=self.name, data=page.get())
463 | self.obj = Page(**created_page)
464 | return self
465 |
466 | def page_update(
467 | self, id_: Optional[str] = None, properties: Optional[Dict[str, PropertyValue]] = None,
468 | title: Optional[Union[str, RichTextArray]] = None, archived: bool = False
469 | ) -> Optional[Element]:
470 | """
471 | :param id_: ID of page
472 | :param properties: dict of existing properties
473 | :param title:
474 | :param archived: set to `True` for delete the page
475 | :return: self.obj -> Page
476 | """
477 | if self.name != "pages":
478 | logger.warning("Method supports `pages` only")
479 | return None
480 | if isinstance(id_, str) and "-" in id_:
481 | id_ = id_.replace("-", "")
482 | if self.obj:
483 | id_ = self.obj.id
484 | patch = {}
485 | if properties:
486 | patch["properties"] = {name: p.get() for name, p in properties.items()}
487 | if title:
488 | patch.setdefault("properties", {})
489 | patch["properties"]["title"] = PropertyValue.create("title", title).get()
490 | # if archived:
491 | patch["archived"] = archived
492 | updated_page = self.api.session.method(method="patch", path=self.name, id_=id_, data=patch)
493 | self.obj = Page(**updated_page)
494 | return self
495 |
496 | def block_update(
497 | self, id_: Optional[str] = None, block_obj: Optional[Block] = None,
498 | new_text: Optional[str] = None, archived: bool = False
499 | ) -> Optional[Element]:
500 | """
501 | Updates text of Block.
502 | `text`, `checked` (`to_do` type), `language` (`code` type) fields support only!
503 | You can modify any attrs of existing block and provide it (Block object) to this func.
504 | Changing the Block type is not supported.
505 |
506 | :param id_: ID of block to change text OR
507 | :param block_obj: modified Block (replace mode only)
508 |
509 | :param new_text: new text (replace mode only)
510 | :param archived: flag to delete that Block
511 | :return: self.obj -> Block
512 |
513 | `blocks = no.blocks.get_block_children("PAGE ID")`
514 | `for b in blocks.obj:`
515 | `no.blocks.block_update(block_obj=b, new_text="OH YEEEAHH")`
516 | `for b in blocks.obj:`
517 | `b.text = "ALL IS DONE"`
518 | `no.blocks.block_update(block_obj=b)`
519 | """
520 | if self.name != "blocks":
521 | logger.warning("Method supports `blocks` only")
522 | return None
523 | if isinstance(id_, str) and "-" in id_:
524 | id_ = id_.replace("-", "")
525 | if self.obj:
526 | id_ = self.obj.id
527 | else:
528 | self.get(id_)
529 | if block_obj:
530 | self.obj = block_obj
531 | if not self.obj.get():
532 | return None
533 | if new_text:
534 | self.obj.text = new_text
535 | patch = {"archived": archived}
536 | patch.update(self.obj.get())
537 | updated_block = self.api.session.method(method="patch", path=self.name, id_=id_, data=patch)
538 | self.obj = Block(**updated_block)
539 | return self
540 |
541 | def block_append(
542 | self,
543 | id_: Optional[str] = None,
544 | block: Optional[Block] = None,
545 | blocks: Optional[Union[BlockArray, List[Block]]] = None,
546 | after: Optional[Union[Block, str]] = None,
547 | ) -> Optional[Element]:
548 | """
549 | Append block or blocks children
550 |
551 | :param id_: provide id of block or page if `self.obj` is empty
552 |
553 | :param block: Block to append OR
554 | :param blocks: List[Block] or BlockArray to append
555 | :param after: the existing block that the new block should be appended after (Block or ID)
556 |
557 | :return: self.obj -> BlockArray
558 |
559 | `p1 = no.pages.get("PAGE ID")`
560 | `p1.block_append(block=Block.create("SOMETHING NEW YO"))`
561 |
562 | `no.blocks.block_append("BLOCK OR PAGE ID", blocks=blocks)`
563 | """
564 | if self.name not in ["blocks", "pages"]:
565 | logger.warning("Method supports `blocks` or `pages` only")
566 | return None
567 | if isinstance(id_, str) and "-" in id_:
568 | id_ = id_.replace("-", "")
569 | if self.obj:
570 | id_ = self.obj.id
571 | if isinstance(blocks, list):
572 | blocks = BlockArray(blocks, create=True)
573 | if isinstance(block, Block):
574 | blocks = BlockArray([block], create=True)
575 | data = {"children": blocks.get()}
576 | if after:
577 | if isinstance(after, Block):
578 | data["after"] = after.id
579 | else:
580 | data["after"] = after
581 |
582 | new_blocks = self.api.session.method(
583 | method="patch", path="blocks", id_=id_, after_path="children", data=data
584 | )
585 | return Element(api=self.api, name="blocks", obj=BlockArray(new_blocks["results"]))
586 |
587 | def get_myself(self) -> Element:
588 | """
589 | Retrieves the bot User associated with the API token provided in the authorization header.
590 |
591 | :return: Element with User obj
592 |
593 | `me = no.users.get_myself()`
594 | """
595 | new_object = Element(self.api, name="users")
596 | new_object.get("me")
597 | return new_object
598 |
599 | def from_linkto(self, linkto: LinkTo, limit: int = 0) -> Optional[Element]:
600 | if not linkto:
601 | logger.error("LinkTo must be provided!")
602 | return None
603 | if not linkto.uri:
604 | logger.error("LinkTo.uri must be provided!")
605 | return None
606 | new_element = Element(self.api, name=linkto.uri)
607 | return new_element.get(linkto.id, getattr(linkto, "after_path", None), limit)
608 |
609 | def from_object(self, model: Union[Database, Page, Block]):
610 | return Element(self.api, model.path, model)
611 |
612 | def __repr__(self):
613 | if not self.obj:
614 | return f"Notion/{self.name}/"
615 | return f"Notion/{self.name}/{self.obj!r}"
616 |
617 | def __str__(self):
618 | return self.__repr__()
619 |
--------------------------------------------------------------------------------
/tests/test_api.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 |
3 | import pytest
4 |
5 | from pytion.models import Page, Block, Database, User, RichTextArray, ElementArray
6 | from pytion.models import BlockArray, PropertyValue, PageArray, LinkTo, Property
7 | from pytion import InvalidRequestURL, ObjectNotFound, ValidationError
8 |
9 |
10 | def test_notion(no):
11 | assert no.version == "2022-06-28"
12 | assert no.session.base == "https://api.notion.com/v1/"
13 |
14 |
15 | def test_search__empty(no):
16 | r = no.search("123412341234")
17 | assert isinstance(r.obj, ElementArray)
18 | assert len(r.obj) == 0
19 |
20 |
21 | def test_search__type_and_limit(no):
22 | r = no.search(object_type="database", limit=4)
23 | assert isinstance(r.obj, ElementArray)
24 | assert len(r.obj) == 4
25 | assert all(isinstance(item, Database) for item in r.obj)
26 |
27 |
28 | def test_search__query(no):
29 | r = no.search("tests")
30 | assert isinstance(r.obj, ElementArray)
31 | assert len(r.obj) >= 1
32 | assert str(r.obj[0]) == "Pytion Tests"
33 |
34 |
35 | class TestElement:
36 | def test_get__page(self, root_page):
37 | page = root_page
38 | assert isinstance(page.obj, Page), "get of .pages. must return Page object"
39 | assert page.obj.id == "878d628488d94894ab14f9b872cd6870"
40 | assert str(page.obj.title) == "Pytion Tests"
41 |
42 | def test_get__block(self, no):
43 | block = no.blocks.get("878d628488d94894ab14f9b872cd6870") # root page
44 | assert isinstance(block.obj, Block)
45 | assert block.obj.id == "878d628488d94894ab14f9b872cd6870"
46 | assert block.obj.text == "Pytion Tests"
47 |
48 | def test_get__database(self, no):
49 | database = no.databases.get("0e9539099cff456d89e44684d6b6c701") # Little Database
50 | assert isinstance(database.obj, Database)
51 | assert database.obj.id == "0e9539099cff456d89e44684d6b6c701"
52 | assert str(database.obj.title) == "Little Database"
53 | assert str(database.obj.description) == "Database has a super description! Don’t touch it!"
54 | assert database.obj.is_inline is False
55 |
56 | def test_get__user(self, no):
57 | user = no.users.get("01c67faf3aba45ffaa022407f87c86a5")
58 | assert isinstance(user.obj, User)
59 | assert user.obj.id == "01c67faf3aba45ffaa022407f87c86a5"
60 | assert user.obj.name == "Yegor Gomzin"
61 |
62 | def test_get__bad_url(self, no):
63 | with pytest.raises(InvalidRequestURL):
64 | no.page.get("878d628488d94894ab14f9b872cd6870") # root page
65 |
66 | def test_get__bad_id(self, no):
67 | with pytest.raises(ObjectNotFound):
68 | no.pages.get("878d628488d94894ab14f9b872cd6872") # random id
69 |
70 | def test_get__after_path_page(self, no):
71 | blocks = no.blocks.get("82ee5677402f44819a5da3302273400a", _after_path="children") # Page with some texts
72 | assert isinstance(blocks.obj, BlockArray)
73 | assert len(blocks.obj) == 3
74 | assert isinstance(blocks.obj[0], Block)
75 | blocks = no.blocks.get("82ee5677402f44819a5da3302273400a", _after_path="children", limit=2) # Page with some te
76 | assert len(blocks.obj) == 2
77 |
78 | def test_get__after_path_block(self, no):
79 | blocks = no.blocks.get("8a920ba7dc1d4961811e5c82b28028ed", _after_path="children") # Hello! How are you?
80 | assert isinstance(blocks.obj, BlockArray)
81 | assert len(blocks.obj) == 3
82 | assert isinstance(blocks.obj[0], Block)
83 |
84 | def test_get_parent__block(self, no):
85 | parent_block = no.blocks.get_parent("9b2026c3a0cb45fc8cee330142d60f3a") # I'm fine!
86 | assert isinstance(parent_block.obj, Block)
87 | assert parent_block.obj.id == "8a920ba7dc1d4961811e5c82b28028ed"
88 | assert str(parent_block.obj) == "Hello! How are you?"
89 |
90 | def test_get_parent__block2(self, no):
91 | parent_block = no.blocks.get_parent("8a920ba7dc1d4961811e5c82b28028ed") # Hello! How are you?
92 | assert isinstance(parent_block.obj, Page)
93 | assert parent_block.obj.id == "82ee5677402f44819a5da3302273400a"
94 | assert str(parent_block.obj) == "Page with some texts"
95 |
96 | def test_get_parent__page(self, no):
97 | parent_page_block = no.pages.get_parent("82ee5677402f44819a5da3302273400a") # Page with some texts
98 | assert isinstance(parent_page_block.obj, Block)
99 | assert parent_page_block.obj.id == "6001eb5621f2428392d532bf08bc8ecd"
100 | assert "Page with some texts" in str(parent_page_block.obj)
101 |
102 | def test_get_parent__database(self, no, root_page):
103 | parent_page_block = no.databases.get_parent("0e9539099cff456d89e44684d6b6c701") # Little Database
104 | assert isinstance(parent_page_block.obj, Page)
105 | assert parent_page_block.obj.id == root_page.obj.id
106 |
107 | def test_get_parent__user(self, no):
108 | something = no.users.get_parent("01c67faf3aba45ffaa022407f87c86a5")
109 | assert something is None, "User object has not any parent"
110 |
111 | def test_get_parent__block_obj(self, no):
112 | block = no.blocks.get("8a920ba7dc1d4961811e5c82b28028ed") # Hello! How are you?
113 | parent_block = block.get_parent()
114 | assert isinstance(parent_block.obj, Page)
115 | assert parent_block.obj.id == "82ee5677402f44819a5da3302273400a"
116 | assert str(parent_block.obj) == "Page with some texts"
117 |
118 | def test_get_parent__page_obj(self, no): # Database is the parent of this page
119 | page = no.pages.get("b85877eaf7bf4245a8c5218055eeb81f") # Parent testing page
120 | database = page.get_parent()
121 | assert isinstance(database.obj, Database)
122 | assert database.obj.id == "0e9539099cff456d89e44684d6b6c701"
123 | assert str(database.obj.title) == "Little Database"
124 |
125 | def test_get_parent__database_obj(self, little_database):
126 | database = little_database # Little Database
127 | parent_page_block = database.get_parent()
128 | assert isinstance(parent_page_block.obj, Page)
129 | assert parent_page_block.obj.id == "878d628488d94894ab14f9b872cd6870"
130 | assert str(parent_page_block.obj) == "Pytion Tests"
131 |
132 | def test_get_parent__child_page(self, no):
133 | child_page = no.blocks.get("878d628488d94894ab14f9b872cd6870") # root page
134 | page = child_page.get_parent()
135 | assert isinstance(page.obj, Page)
136 | assert page.obj.id == "878d628488d94894ab14f9b872cd6870"
137 | assert str(page.obj.title) == "Pytion Tests"
138 |
139 | def test_get_parent__child_database(self, no):
140 | child_database = no.blocks.get("0e9539099cff456d89e44684d6b6c701") # Little Database
141 | database = child_database.get_parent()
142 | assert isinstance(database.obj, Database)
143 | assert database.obj.id == "0e9539099cff456d89e44684d6b6c701"
144 | assert str(database.obj.title) == "Little Database"
145 |
146 | def test_get_parent__workspace(self, root_page):
147 | workspace = root_page.get_parent()
148 | assert workspace is None
149 |
150 | def test_get_block_children__page_id(self, no):
151 | blocks = no.pages.get_block_children("82ee5677402f44819a5da3302273400a") # Page with some texts
152 | assert isinstance(blocks.obj, BlockArray)
153 | assert len(blocks.obj) == 3
154 | assert isinstance(blocks.obj[0], Block)
155 |
156 | def test_get_block_children__page_obj(self, page_some_texts):
157 | page = page_some_texts # Page with some texts
158 | blocks = page.get_block_children()
159 | assert isinstance(blocks.obj, BlockArray)
160 | assert len(blocks.obj) == 3
161 | assert isinstance(blocks.obj[0], Block)
162 |
163 | def test_get_block_children__block_id(self, no):
164 | blocks = no.blocks.get_block_children("8a920ba7dc1d4961811e5c82b28028ed") # Hello! How are you?
165 | assert isinstance(blocks.obj, BlockArray)
166 | assert len(blocks.obj) == 3
167 | assert isinstance(blocks.obj[0], Block)
168 |
169 | def test_get_block_children__block_obj(self, no):
170 | block = no.blocks.get("8a920ba7dc1d4961811e5c82b28028ed") # Hello! How are you?
171 | blocks = block.get_block_children()
172 | assert isinstance(blocks.obj, BlockArray)
173 | assert len(blocks.obj) == 3
174 | assert isinstance(blocks.obj[0], Block)
175 |
176 | def test_get_block_children__database_id(self, no):
177 | something = no.databases.get_block_children("0e9539099cff456d89e44684d6b6c701") # Little Database
178 | assert something is None, "Database has no children"
179 |
180 | def test_get_block_children__database_obj(self, little_database):
181 | database = little_database # Little Database
182 | something = database.get_block_children()
183 | assert something is None, "Database has no children"
184 |
185 | def test_get_block_children__child_database(self, no):
186 | database_block = no.blocks.get("0e9539099cff456d89e44684d6b6c701") # Little Database
187 | database = database_block.get_block_children()
188 | assert isinstance(database.obj, Database)
189 | assert database.obj.id == "0e9539099cff456d89e44684d6b6c701"
190 | assert str(database.obj.title) == "Little Database"
191 |
192 | def test_get_block_children_recursive__page_id(self, no):
193 | blocks = no.pages.get_block_children_recursive("82ee5677402f44819a5da3302273400a") # Page with some texts
194 | assert isinstance(blocks.obj, BlockArray)
195 | assert len(blocks.obj) == 6
196 | assert isinstance(blocks.obj[0], Block)
197 |
198 | def test_get_block_children_recursive__page_obj(self, page_some_texts):
199 | page = page_some_texts # Page with some texts
200 | blocks = page.get_block_children_recursive()
201 | assert isinstance(blocks.obj, BlockArray)
202 | assert len(blocks.obj) == 6
203 | assert isinstance(blocks.obj[0], Block)
204 |
205 | def test_get_block_children_recursive__block_id(self, no):
206 | blocks = no.blocks.get_block_children_recursive("8a920ba7dc1d4961811e5c82b28028ed") # Hello! How are you?
207 | assert isinstance(blocks.obj, BlockArray)
208 | assert len(blocks.obj) == 3
209 | assert isinstance(blocks.obj[0], Block)
210 |
211 | def test_get_block_children_recursive__block_obj(self, no):
212 | block = no.blocks.get("8a920ba7dc1d4961811e5c82b28028ed") # Hello! How are you?
213 | blocks = block.get_block_children_recursive()
214 | assert isinstance(blocks.obj, BlockArray)
215 | assert len(blocks.obj) == 3
216 | assert isinstance(blocks.obj[0], Block)
217 |
218 | def test_get_block_children_recursive__database_id(self, no):
219 | something = no.databases.get_block_children_recursive("0e9539099cff456d89e44684d6b6c701") # Little Database
220 | assert something is None, "Database has no children"
221 |
222 | def test_get_block_children_recursive__database_obj(self, little_database):
223 | database = little_database # Little Database
224 | something = database.get_block_children_recursive()
225 | assert something is None, "Database has no children"
226 |
227 | def test_get_block_children_recursive__child_database(self, no):
228 | database_block = no.blocks.get("0e9539099cff456d89e44684d6b6c701") # Little Database
229 | database = database_block.get_block_children_recursive()
230 | assert isinstance(database.obj, Database)
231 | assert database.obj.id == "0e9539099cff456d89e44684d6b6c701"
232 | assert str(database.obj.title) == "Little Database"
233 |
234 | def test_get_block_children_recursive__force(self, no):
235 | block = no.blocks.get("8a920ba7dc1d4961811e5c82b28028ed") # Hello! How are you?
236 | blocks = block.get_block_children_recursive(force=True)
237 | assert isinstance(blocks.obj, BlockArray)
238 | assert len(blocks.obj) == 5
239 | assert isinstance(blocks.obj[0], Block)
240 |
241 | def test_get_block_children_recursive__max_depth(self, page_some_texts):
242 | page = page_some_texts # Page with some texts
243 | blocks = page.get_block_children_recursive(force=True, max_depth=2)
244 | assert isinstance(blocks.obj, BlockArray)
245 | assert len(blocks.obj) == 7
246 | assert isinstance(blocks.obj[0], Block)
247 |
248 | def test_get_page_property__page_id(self, no):
249 | p = no.pages.get_page_property("%7Dma%3F", "b85877eaf7bf4245a8c5218055eeb81f")
250 | assert isinstance(p.obj, PropertyValue)
251 | assert len(p.obj.value) == 2
252 | assert p.obj.type == "multi_select"
253 |
254 | def test_get_page_property__page_obj(self, no):
255 | page = no.pages.get("b85877eaf7bf4245a8c5218055eeb81f")
256 | p = page.get_page_property("%7Dma%3F")
257 | assert isinstance(p.obj, PropertyValue)
258 | assert len(p.obj.value) == 2
259 | assert p.obj.type == "multi_select"
260 |
261 | def test_get_page_property__bad_id(self, no):
262 | with pytest.raises(ValidationError):
263 | no.pages.get_page_property("%7Dma%3A", "b85877eaf7bf4245a8c5218055eeb81f")
264 |
265 | def test_get_page_property__bad_page(self, no):
266 | with pytest.raises(ObjectNotFound):
267 | no.pages.get_page_property("%7Dma%3F", "b85877eaf7bf4245a8c5218055eeb81a")
268 |
269 | def test_get_page_properties(self, no):
270 | page = no.pages.get("b85877eaf7bf4245a8c5218055eeb81f") # Parent testing page
271 | assert isinstance(page.obj, Page)
272 | # assert str(page.obj) == "unknown"
273 | # assert isinstance(page.obj.properties["Done"], Property)
274 | page.get_page_properties()
275 | assert isinstance(page.obj.properties["Done"], PropertyValue)
276 | assert page.obj.properties["Digit"].value == 2
277 | assert "tag1" in page.obj.properties["Tags"].value
278 |
279 | def test_get_page_properties__title(self, no):
280 | page = no.pages.get("b85877eaf7bf4245a8c5218055eeb81f") # Parent testing page
281 | assert isinstance(page.obj, Page)
282 | # assert str(page.obj) == "unknown"
283 | # assert isinstance(page.obj.properties["Done"], Property)
284 | page.get_page_properties(title_only=True)
285 | # assert hasattr(page.obj.properties["by"], "value") is False
286 | # assert isinstance(page.obj.properties["Done"], Property)
287 | assert str(page.obj.title) == "Parent testing page"
288 |
289 | def test_db_query__id(self, no):
290 | pages = no.databases.db_query("0e9539099cff456d89e44684d6b6c701") # Little Database
291 | assert isinstance(pages.obj, PageArray)
292 | assert len(pages.obj) == 4
293 | assert str(pages.obj[0].title) == ""
294 |
295 | def test_db_query__obj(self, little_database):
296 | pages = little_database.db_query(limit=3)
297 | assert isinstance(pages.obj, PageArray)
298 | assert len(pages.obj) == 3
299 | assert str(pages.obj[0].title) == ""
300 |
301 | def test_db_filter__title_ez(self, little_database):
302 | pages = little_database.db_filter("testing page")
303 | assert isinstance(pages.obj, PageArray)
304 | assert len(pages.obj) == 1
305 | assert str(pages.obj[0].title) == "Parent testing page"
306 |
307 | def test_db_filter__not_contain(self, little_database):
308 | pages = little_database.db_filter("testing page", condition="does_not_contain")
309 | assert isinstance(pages.obj, PageArray)
310 | assert len(pages.obj) == 3
311 | assert str(pages.obj[0].title) == ""
312 |
313 | def test_db_filter__ends_with(self, little_database):
314 | pages = little_database.db_filter(
315 | property_name="Name", property_type="title", value="what?", condition="ends_with"
316 | )
317 | assert isinstance(pages.obj, PageArray)
318 | assert len(pages.obj) == 1
319 | assert str(pages.obj[0].title) == "wait, what?"
320 |
321 | def test_db_filter__is_empty(self, little_database):
322 | pages = little_database.db_filter(property_name="title", property_type="title", condition="is_empty")
323 | assert isinstance(pages.obj, PageArray)
324 | assert len(pages.obj) == 1
325 | assert str(pages.obj[0].title) == ""
326 |
327 | def test_db_filter__greater_than(self, little_database):
328 | pages = little_database.db_filter(
329 | property_name="Digit", property_type="number", condition="greater_than", value="1"
330 | )
331 | assert isinstance(pages.obj, PageArray)
332 | assert len(pages.obj) == 2
333 | assert str(pages.obj[0].title) == "We are best friends, body"
334 |
335 | def test_db_filter__checkbox(self, little_database):
336 | pages = little_database.db_filter(property_name="Done", property_type="checkbox")
337 | assert isinstance(pages.obj, PageArray)
338 | assert len(pages.obj) == 1
339 | assert str(pages.obj[0].title) == "We are best friends, body"
340 |
341 | def test_db_filter__contains_tag(self, little_database):
342 | pages = little_database.db_filter(
343 | property_name="Tags", property_type="multi_select", value="tag1"
344 | )
345 | assert isinstance(pages.obj, PageArray)
346 | assert len(pages.obj) == 2
347 | assert str(pages.obj[0].title) == ""
348 |
349 | def test_db_filter__notcontains_tag(self, little_database):
350 | pages = little_database.db_filter(
351 | property_name="Tags", property_type="multi_select", value="tag2", condition="does_not_contain"
352 | )
353 | assert isinstance(pages.obj, PageArray)
354 | assert len(pages.obj) == 3
355 | assert str(pages.obj[0].title) == ""
356 |
357 | def test_db_filter__no_tags(self, little_database):
358 | pages = little_database.db_filter(
359 | property_name="Tags", property_type="multi_select", condition="is_empty"
360 | )
361 | assert isinstance(pages.obj, PageArray)
362 | assert len(pages.obj) == 1
363 | assert str(pages.obj[0].title) == "wait, what?"
364 |
365 | def test_db_filter__tag_property_obj(self, no, little_database):
366 | page = no.pages.get("c2fc6b3dc3d244e9be2a3d28b26082bf") # Untitled
367 | my_prop = page.obj.properties["Tags"]
368 | pages = little_database.db_filter(property_obj=my_prop)
369 | assert isinstance(pages.obj, PageArray)
370 | assert len(pages.obj) == 2
371 | assert str(pages.obj[0].title) == ""
372 |
373 | def test_db_filter__without_filter(self, little_database):
374 | pages = little_database.db_filter("")
375 | assert isinstance(pages.obj, PageArray)
376 | assert len(pages.obj) == 4
377 | assert str(pages.obj[0].title) == ""
378 |
379 | def test_db_filter__date_after(self, little_database):
380 | pages = little_database.db_filter(
381 | property_name="created", property_type="date", condition="on_or_after", value="2022-04-22"
382 | )
383 | assert isinstance(pages.obj, PageArray)
384 | assert len(pages.obj) == 2
385 | assert str(pages.obj[0].title) == ""
386 |
387 | def test_db_filter__date_next_year(self, little_database):
388 | pages = little_database.db_filter(
389 | property_name="created", property_type="created_time", condition="next_year", value="2022-04-22"
390 | )
391 | assert isinstance(pages.obj, PageArray)
392 | assert len(pages.obj) == 0
393 |
394 | def test_db_filter__date_this_week(self, little_database):
395 | pages = little_database.db_filter(
396 | property_name="created", property_type="created_time", condition="this_week"
397 | )
398 | assert isinstance(pages.obj, PageArray)
399 | assert len(pages.obj) == 0
400 |
401 | def test_db_filter__status(self, little_database):
402 | pages = little_database.db_filter(
403 | property_name="Status", property_type="status", value="Done"
404 | )
405 | assert isinstance(pages.obj, PageArray)
406 | assert len(pages.obj) == 1
407 | assert str(pages.obj[0].title) == "wait, what?"
408 |
409 | def test_db_filter__sort_desc(self, little_database):
410 | pages = little_database.db_filter("", descending="created")
411 | assert isinstance(pages.obj, PageArray)
412 | assert len(pages.obj) == 4
413 | assert str(pages.obj[0].title) == ""
414 | assert str(pages.obj[2].title) == "We are best friends, body"
415 |
416 | def test_db_filter__sort_asc(self, little_database):
417 | pages = little_database.db_filter("", ascending="Digit")
418 | assert isinstance(pages.obj, PageArray)
419 | assert len(pages.obj) == 4
420 | assert str(pages.obj[0].title) == "wait, what?"
421 | assert str(pages.obj[2].title) == "We are best friends, body"
422 |
423 | def test_db_create(self, no):
424 | parent = LinkTo.create(page_id="2dff77eb43d44ce097ffb421499f82aa") # Page for creating databases
425 | properties = {
426 | "Name": Property.create("title"),
427 | "Digit": Property.create("number"),
428 | "Status": Property.create("select"),
429 | }
430 | title = "DB 1"
431 | description = "ABCDEF"
432 | database = no.databases.db_create(parent=parent, properties=properties, title=title, description=description)
433 | assert isinstance(database.obj, Database)
434 | assert str(database.obj.title) == title
435 | assert "Status" in database.obj.properties
436 | assert str(database.obj.description) == description
437 |
438 | # Delete database manually. There is no way to delete a database by API
439 |
440 | def test_db_update__rename_title(self, database_for_updates):
441 | old_title = str(database_for_updates.obj.title)
442 | new_title = "1 BDU"
443 | database = database_for_updates.db_update(title=new_title)
444 | assert isinstance(database.obj, Database)
445 | assert str(database.obj.title) == new_title
446 |
447 | old_database = database_for_updates.db_update(title=old_title)
448 | assert str(old_database.obj.title) == old_title
449 |
450 | def test_db_update__rename_prop(self, database_for_updates):
451 | properties = {"Name": Property.create(type_="title", name="Subject")}
452 | database = database_for_updates.db_update(properties=properties)
453 | assert "Subject" in database.obj.properties
454 |
455 | title_property = database.obj.properties["Subject"]
456 | title_property.name = "Name"
457 | old_properties = {title_property.id: title_property}
458 | old_database = database.db_update(properties=old_properties)
459 | assert "Name" in old_database.obj.properties
460 |
461 | def test_db_update__retype_prop(self, database_for_updates):
462 | properties = {"Tags": Property.create("select")}
463 | database = database_for_updates.db_update(properties=properties)
464 | assert database.obj.properties["Tags"].type == "select"
465 |
466 | old_properties = {"Tags": Property.create("multi_select")}
467 | old_database = database_for_updates.db_update(properties=old_properties)
468 | assert old_database.obj.properties["Tags"].type == "multi_select"
469 |
470 | def test_db_update__create_delete_prop(self, database_for_updates):
471 | properties = {"New property": Property.create("checkbox")}
472 | database = database_for_updates.db_update(properties=properties)
473 | assert "New property" in database.obj.properties
474 | assert database.obj.properties["New property"].type == "checkbox"
475 |
476 | properties["New property"] = Property.create(None)
477 | database = database.db_update(properties=properties)
478 | assert "New property" not in database.obj.properties
479 |
480 | def test_page_create__into_page(self, no, page_for_pages):
481 | parent = LinkTo(from_object=page_for_pages.obj)
482 | page = no.pages.page_create(parent=parent, title="Page 1")
483 | assert isinstance(page.obj, Page)
484 | assert str(page.obj.title) == "Page 1"
485 | # delete section
486 | delete_page = page.page_update(archived=True)
487 | assert delete_page.obj.archived is True
488 |
489 | def test_page_create__into_database(self, no):
490 | parent = LinkTo.create(database_id="35f50aa293964b0d93e09338bc980e2e") # Database for creating pages
491 | page = no.pages.page_create(parent=parent, title="Page 2")
492 | assert isinstance(page.obj, Page)
493 | assert str(page.obj.title) == "Page 2"
494 | # delete section
495 | delete_page = page.page_update(archived=True)
496 | assert delete_page.obj.archived is True
497 |
498 | def test_page_create__into_database_props(self, no):
499 | parent = LinkTo.create(database_id="35f50aa293964b0d93e09338bc980e2e") # Database for creating pages
500 | props = {
501 | "Tags": PropertyValue.create(type_="multi_select", value=["tag1", "tag2"]),
502 | "done": PropertyValue.create("checkbox", True),
503 | "when": PropertyValue.create("date", datetime.now()),
504 | }
505 | page = no.pages.page_create(parent=parent, properties=props, title="Page 3")
506 | assert isinstance(page.obj, Page)
507 | assert str(page.obj.title) == "Page 3"
508 | # delete section
509 | delete_page = page.page_update(archived=True)
510 | assert delete_page.obj.archived is True
511 |
512 | def test_page_create__with_children(self, no, page_for_pages):
513 | parent = LinkTo(from_object=page_for_pages.obj)
514 | child = Block.create("Hello, World!")
515 | page = no.pages.page_create(parent=parent, title="Page 4", children=[child])
516 | assert isinstance(page.obj, Page)
517 | assert str(page.obj.title) == "Page 4"
518 | blocks = page.get_block_children()
519 | assert isinstance(blocks.obj, BlockArray)
520 | assert len(blocks.obj) == 1
521 | assert isinstance(blocks.obj[0], Block)
522 | assert str(blocks.obj[0].text) == "Hello, World!"
523 | # delete section
524 | delete_page = page.page_update(archived=True)
525 | assert delete_page.obj.archived is True
526 |
527 | def test_page_create__from_obj(self, no, page_for_pages):
528 | parent = LinkTo(from_object=page_for_pages.obj)
529 | page_obj = Page.create(parent=parent, title="Page 5")
530 | page = no.pages.page_create(page_obj=page_obj)
531 | assert isinstance(page.obj, Page)
532 | assert str(page.obj.title) == "Page 5"
533 | # delete section
534 | delete_page = page.page_update(archived=True)
535 | assert delete_page.obj.archived is True
536 |
537 | def test_page_update__rename(self, page_for_updates):
538 | old_name = str(page_for_updates.obj.title)
539 | new_name = "Updating for page"
540 | page = page_for_updates.page_update(title=new_name)
541 | assert isinstance(page.obj, Page)
542 | assert str(page.obj.title) == new_name
543 |
544 | old_page = page.page_update(title=RichTextArray.create(old_name))
545 | assert str(old_page.obj.title) == old_name
546 |
547 | def test_page_update__change_props(self, page_for_updates):
548 | old_props = page_for_updates.obj.properties
549 | new_props = {
550 | "Tags": PropertyValue.create("multi_select", ["tag2"]),
551 | "done": PropertyValue.create("checkbox", False),
552 | "when": PropertyValue.create("date", datetime.now()),
553 | }
554 | page = page_for_updates.page_update(properties=new_props)
555 | assert isinstance(page.obj, Page)
556 | assert "tag2" in page.obj.properties["Tags"].value
557 | assert page.obj.properties["done"].value is False
558 |
559 | old_page = page.page_update(properties=old_props)
560 | assert "tag1" in old_page.obj.properties["Tags"].value
561 | assert old_page.obj.properties["done"].value is True
562 |
563 | def test_page_update__delete(self, page_for_updates):
564 | page = page_for_updates.page_update(archived=True)
565 | assert isinstance(page.obj, Page)
566 | assert page.obj.archived is True
567 |
568 | old_page = page.page_update(archived=False)
569 | assert old_page.obj.archived is False
570 |
571 | def test_block_update__rename(self, no):
572 | block = no.blocks.get("08326405c2924ccc929bd78ceb70a2f3") # Paragraph block to update.
573 | old_name = str(block.obj.text)
574 | new_name = old_name + old_name
575 | new_block = no.blocks.block_update(id_="08326405c2924ccc929bd78ceb70a2f3", new_text=new_name)
576 | assert isinstance(new_block.obj, Block)
577 | assert str(new_block.obj.text) == new_name
578 |
579 | old_block = new_block.block_update(new_text=old_name)
580 | assert str(old_block.obj.text) == old_name
581 |
582 | def test_block_update__delete(self, no):
583 | block = no.blocks.get("08326405c2924ccc929bd78ceb70a2f3") # Paragraph block to update.
584 | new_block = block.block_update(archived=True)
585 | assert isinstance(new_block.obj, Block)
586 | assert new_block.obj.archived is True
587 |
588 | old_block = new_block.block_update(archived=False)
589 | assert old_block.obj.archived is False
590 |
591 | def test_block_update__obj_retype(self, no):
592 | block_obj = Block.create("To do block", type_="to_do")
593 | with pytest.raises(ValidationError):
594 | no.blocks.block_update(id_="08326405c2924ccc929bd78ceb70a2f3", block_obj=block_obj)
595 |
596 | def test_block_update__obj(self, no):
597 | block = no.blocks.get("08326405c2924ccc929bd78ceb70a2f3") # Paragraph block to update.
598 | old_block_obj = block.obj
599 | new_name = "Updated paragraph block"
600 | block_obj = Block.create(new_name)
601 | new_block = block.block_update(block_obj=block_obj)
602 | assert isinstance(new_block.obj, Block)
603 | assert new_block.obj.simple == new_name
604 |
605 | old_block = new_block.block_update(block_obj=old_block_obj)
606 | assert str(old_block.obj) == old_block_obj.simple
607 |
608 | def test_block_append__single(self, no):
609 | page = no.pages.get("365985ab349149d7826035fd46858b3f") # Page for creating blocks
610 | my_block = Block.create("Such wow!")
611 | blocks = page.block_append(block=my_block)
612 | assert isinstance(blocks.obj, BlockArray)
613 |
614 | blocks = page.get_block_children()
615 | assert len(blocks.obj) == 1
616 | assert str(blocks.obj[0].text) == "Such wow!"
617 | remove_block = blocks.from_object(blocks.obj[0])
618 | removed_block = remove_block.block_update(archived=True)
619 | assert removed_block.obj.archived is True
620 |
621 | def test_block_append__many(self, no):
622 | my_block1 = Block.create("Do simple tests", type_="to_do", checked=True)
623 | my_block2 = Block.create(
624 | "multiline:\n code: text", type_="code", caption="is it YAML?", language="yaml"
625 | )
626 | blocks = no.blocks.block_append("365985ab349149d7826035fd46858b3f", blocks=[my_block1, my_block2])
627 | assert isinstance(blocks.obj, BlockArray)
628 |
629 | blocks = no.pages.get_block_children("365985ab349149d7826035fd46858b3f")
630 | assert len(blocks.obj) == 2
631 | assert str(blocks.obj[0].text) == "[x] Do simple tests"
632 | assert str(blocks.obj[1].caption) == "is it YAML?"
633 | assert blocks.obj[1].language == "yaml"
634 |
635 | for block in blocks.obj:
636 | removed_block = no.blocks.block_update(block.id, archived=True)
637 | assert removed_block.obj.archived is True
638 |
639 | def test_block_append__insert(self, no):
640 | page = no.pages.get("36223246a20e42df8f9b354ed1f11d75") # Page for updating
641 | existing_block = no.blocks.get("60c20e13d2ae4ccbb81b5f8f2c532319") # Queeery tests
642 | my_block = Block.create("Such wow!")
643 | blocks = page.block_append(block=my_block, after=existing_block.obj)
644 | assert isinstance(blocks.obj, BlockArray)
645 |
646 | blocks = page.get_block_children()
647 | assert str(blocks.obj[1].text) == "Such wow!"
648 | remove_block = blocks.from_object(blocks.obj[1])
649 | removed_block = remove_block.block_update(archived=True)
650 | assert removed_block.obj.archived is True
651 |
652 | def test_get_myself(self, no):
653 | bot = no.users.get_myself()
654 | assert isinstance(bot.obj, User)
655 | assert bot.obj.type == "bot"
656 | assert bot.obj.name == "Pytion tests"
657 | assert bot.obj.workspace_name == "Yegor's Workspace"
658 |
659 | def test_get_myself__from_obj(self, root_page):
660 | bot = root_page.get_myself()
661 | assert isinstance(bot.obj, User)
662 | assert bot.obj.type == "bot"
663 | assert bot.obj.name == "Pytion tests"
664 | assert bot.obj.workspace_name == "Yegor's Workspace"
665 |
666 | def test_from_linkto__base(self, no):
667 | link = LinkTo.create(page_id="878d628488d94894ab14f9b872cd6870")
668 | page = no.pages.from_linkto(link)
669 | assert isinstance(page.obj, Page)
670 | assert page.obj.id == "878d628488d94894ab14f9b872cd6870"
671 | assert str(page.obj) == "Pytion Tests"
672 |
673 | def test_from_linkto__child(self, page_some_texts):
674 | child = page_some_texts.from_linkto(page_some_texts.obj.children)
675 | assert isinstance(child.obj, BlockArray)
676 | assert len(child.obj) == 3
677 | assert isinstance(child.obj[0], Block)
678 |
679 | def test_from_linkto__parent(self, no, little_database):
680 | page = no.pages.get("b85877eaf7bf4245a8c5218055eeb81f") # Parent testing page
681 | parent = page.from_linkto(page.obj.parent)
682 | assert isinstance(parent.obj, Database)
683 | assert parent.obj.id == little_database.obj.id
684 | assert str(parent.obj.title) == str(little_database.obj.title)
685 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # pytion
2 |
3 | [](https://pypi.org/project/pytion)
4 | 
5 | 
6 | [](LICENSE)
7 |
8 | Independent unofficial **Python client** for the official **Notion API** (for internal integrations only)
9 |
10 | Client is built with its own object model based on API
11 |
12 | So if you are using **notion.so** and want to automate some stuff with the original API, you're welcome!
13 | You can read any available data, create basic models, and even work with databases.
14 |
15 | Current Notion API version = **"2022-06-28"**
16 |
17 | _*does not use notion-sdk-py client_
18 |
19 | See [Change Log](./CHANGELOG.md)
20 |
21 | # Contents
22 |
23 | 1. [Quick Start](#quick-start)
24 | 2. [Pytion API](#pytion-api)
25 | 1. [Searching](#search)
26 | 2. [pytion.api.Element](#pytionapielement)
27 | 3. [Models](#models)
28 | 1. [pytion.models](#pytionmodels)
29 | 2. [Supported Property types](#supported-property-types)
30 | 3. [Supported block types](#supported-block-types)
31 | 1. [Block creating examples](#block-creating-examples)
32 | 2. [Block deleting](#block-deleting)
33 | 4. [Database operations](#database-operations)
34 | 1. [Retrieving](#retrieving)
35 | 2. [Appending (creating a Page)](#appending-creating-a-page)
36 | 3. [Property Values](#property-values)
37 | 4. [Logging](#logging)
38 |
39 | # Quick start
40 |
41 | ```
42 | pip install pytion
43 | ```
44 |
45 | Create new integration and get your Notion API Token at notion.so -> [here](https://www.notion.com/my-integrations).
46 | Add your new integration 'manager' to your pages or databases by going to the page's menu (three dots), at the bottom of the menu clicking on Add connections and then searching for you new Integration.
47 |
48 | ```python
49 | from pytion import Notion; no = Notion(token=SOME_TOKEN)
50 | ```
51 |
52 | Or put your token for Notion API into file `token` at script directory and use simple `no = Notion()`
53 |
54 | ```python
55 | from pytion import Notion
56 | no = Notion(token=SOME_TOKEN)
57 | page = no.pages.get("PAGE ID") # retrieve page data (not content) and create object
58 | blocks = page.get_block_children() # retrieve page content and create list of objects
59 | database = no.databases.get("Database ID") # retrieve database data (not content) and create object
60 | # retrieve database content by filtering with sorting
61 | pages = database.db_filter(property_name="Done", property_type="checkbox", value=False, descending="title")
62 | ```
63 |
64 | ```
65 | In [1]: from pytion import Notion
66 |
67 | In [2]: no = Notion(token=SOME_TOKEN)
68 |
69 | In [3]: page = no.pages.get("a458613160da45fa96367c8a594297c7")
70 | In [4]: print(page)
71 | Notion/pages/Page(Example page)
72 |
73 | In [5]: blocks = page.get_block_children_recursive()
74 |
75 | In [6]: print(blocks)
76 | Notion/blocks/BlockArray(## Migration planning [x] Rese)
77 |
78 | In [7]: print(blocks.obj)
79 | ## Migration planning
80 | [x] Reset new switch 2022-05-12T00:00:00.000+03:00 → 2022-05-13T01:00:00.000+03:00
81 | - reboot
82 | - hold reset button
83 | [x] Connect to console with baud rate 9600
84 | [ ] Skip default configuration dialog
85 | Use LinkTo(configs)
86 | [Integration changes](https://developers.notion.com/changelog?page=2)
87 |
88 | In [8]: print(blocks.obj.simple)
89 | Migration planning
90 | Reset new switch 2022-05-12T00:00:00.000+03:00 → 2022-05-13T01:00:00.000+03:00
91 | reboot
92 | hold reset button
93 | Connect to console with baud rate 9600
94 | Skip default configuration dialog
95 | Use https://api.notion.com/v1/pages/90ea1231865f4af28055b855c2fba267
96 | https://developers.notion.com/changelog?page=2
97 | ```
98 |
99 | # Pytion API
100 |
101 | Almost all operations are carried out through `Notion` or `Element` object:
102 |
103 | ```python
104 | page = no.pages.get("a458613160da45fa96367c8a594297c7")
105 |
106 | # no -> Notion
107 | # pages -> URI in https://api.notion.com/v1/PAGES/a458613160da45fa96367c8a594297c7
108 | # get -> pytion API method
109 | # page -> Element
110 | # page.obj -> Page (main data structure)
111 | ```
112 |
113 | so:
114 |
115 | - `isinstance(no, Notion) == True`
116 | - `isinstance(no.pages, Element) == True`
117 | - `isinstance(no.databases, Element) == True`
118 | - `isinstance(page, Element) == True`
119 | - `isinstance(page.obj, Page) == True`
120 |
121 | and if you want to retrieve a database - you must use _"databases"_ URI
122 |
123 | ```python
124 | database = no.databases.get("123412341234")
125 | ```
126 |
127 | and the same applies for _"blocks"_ and _"users"_. Valid URI-s are:
128 |
129 | - _pages_
130 | - _blocks_
131 | - _databases_
132 | - _users_
133 |
134 | When you work with existing `Element` object like `page` above, all [methods](#pytionapielement) below will be applied to this Page:
135 |
136 | ```python
137 | new_page = page.page_update(title="new page name 2")
138 |
139 | # new_page is not a new page, it is updated page
140 | # new_page.obj is equal page.obj except title and last_edited properties
141 | ```
142 |
143 | ## Search
144 |
145 | There is a search example:
146 | ```python
147 | no = Notion(token)
148 |
149 | r = no.search("updating", object_type="page")
150 | print(r.obj)
151 | # output:
152 | # Page for updating
153 | # Page to updating databases
154 | ```
155 |
156 |
157 | ## pytion.api.Element
158 |
159 | There is a list of available methods for communicate with **api.notion.com**. These methods are better structured in [next chapter](#pytionmodels).
160 |
161 | `.get(id_)` - Get Element by ID.
162 |
163 | `.get_parent(id_)` - Get parent object of current object if possible.
164 |
165 | `.get_block_children(id_, limit)` - Get children Block objects of current Block object (tabulated texts) if exist.
166 |
167 | `.get_block_children_recursive(id_, max_depth, limit, force)` - Get children Block objects of current Block object (tabulated texts) if exist recursive.
168 |
169 | `.get_page_property(property_id, id_, limit)` - Retrieve a page property item.
170 |
171 | `.get_page_properties(title_only, obj)` - Retrieve the title or all properties of current Page or Page `obj`
172 | *(deprecated, useful for v1.3.0 only)*
173 |
174 | `.db_query(id_, limit, filter_, sorts)` - Query Database.
175 |
176 | `.db_filter(...see desc...)` - Query Database.
177 |
178 | `.db_create(database_obj, parent, properties, title)` - Create Database.
179 |
180 | **_There is no way to delete a database object yet!_**
181 |
182 | `.db_update(id_, title, properties)` - Update Database.
183 |
184 | `.page_create(page_obj, parent, properties, title)` - Create Page.
185 |
186 | `.page_update(id_, properties, title, archived)` - Update Page.
187 |
188 | `.block_update(id_, block_obj, new_text, archived)` - Update text in Block.
189 |
190 | `.block_append(id_, block, blocks, after)` - Append block or blocks children.
191 |
192 | `.get_myself()` - Retrieve my bot User.
193 |
194 | `.from_linkto(linkto)` - Creates new Element object based on LinkTo information.
195 |
196 | `.from_object(model)` - Creates new Element object from Page, Block or Database object. Usable while Element object contains an Array.
197 |
198 | > More details and usage examples of these methods you can see into func descriptions.
199 |
200 | # Models
201 |
202 | ### pytion.models
203 |
204 | There are classes **based on API** structures:
205 |
206 | - `RichText` based on [Rich text object](https://developers.notion.com/reference/rich-text)
207 | - `RichTextArray` is a list of RichText objects with useful methods
208 | - You can create object by simple `RichTextArray.create("My title text")` and then use it in any methods
209 | - Any Rich Text getting from API will be RichTextArray
210 | - `str()` returns plain text of all "Rich Texts". ez
211 | - `+` operator is available with `str` and `RichTextArray`
212 | - `.simple` property returns stripped plain text without any markdown syntax. useful for URL
213 | - `Database` based on [Database object](https://developers.notion.com/reference/database)
214 | - You can create object `Database.create(...)` and/or use `.db_create(...)` API method
215 | - attrs represent API model. Complex structures like `created_by` are wrapped in internal objects
216 | - use `.db_update()` API method for modify a real database (for ex. properties or title)
217 | - use `.db_query()` to get all database content (it will be `PageArray`)
218 | - use `.db_filter()` to get database content with filtering and/or sorting
219 | - has `.description` attr
220 | - has `.is_inline` attr with the value True if the database appears in the page as an inline block
221 | - has `.public_url` attr when a page or database has been shared publicly
222 | - `Page` based on [Page object](https://developers.notion.com/reference/page)
223 | - You can create object `Page.create(...)` and/or use `.page_create(...)` API method
224 | - use `.page_update()` method to modify attributes or delete the page
225 | - use `.get_block_children()` to get page content (without nested blocks) (it will be `BlockArray`)
226 | - use `.get_block_children_recursive()` to get page content with nested blocks
227 | - use `.get_page_property()` to retrieve the specific `PropertyValue` of the page
228 | - has `.public_url` attr when a page or database has been shared publicly
229 | - `Block` based on [Block object](https://developers.notion.com/reference/block)
230 | - You can create object `Block.create(...)` of specific type from [_support matrix_](#supported-block-types) below and then use it while creating pages or appending
231 | - use `.block_update()` to replace content or change _extension attributes_ or delete the block
232 | - use `.block_append()` to add a new block to a page or add a nested block to another block
233 | - use `.get_block_children()` to get first level nested blocks
234 | - use `.get_block_children_recursive()` to get all levels nested blocks
235 | - `User` based on [User object](https://developers.notion.com/reference/user)
236 | - You can create object `User.create(...)` and use it in some properties like `people` type property
237 | - You can retrieve more data about a User by his ID using `.get()`
238 | - use `.get_myself()` to retrieve the current bot User
239 | - has `.workspace_name` attr for `bot` type users
240 | - `Property` based on [Property object](https://developers.notion.com/reference/property-object)
241 | - You can create object `Property.create(...)` while creating or editing database: `.db_create()` or `.db_update()`
242 | - `formula` type properties configuration is not supported
243 | - `PropertyValue` based on [Property values](https://developers.notion.com/reference/property-value-object)
244 | - You can create object `PropertyValue.create(...)` to set or edit page properties by `.page_create()` or `.page_update()`
245 | - `files`, `formula`, `rollup` type properties are not editable
246 |
247 | There are also useful **internal** classes:
248 |
249 | - `BlockArray` is found when API returns page content in "list of blocks" format
250 | - it is useful to represent all content by `str()`
251 | - also it has `simple` property like `RichTextArray` object
252 | - it automatically indents `str` output of nested blocks
253 | - `PageArray` is found when API returns the result of database query (list of pages)
254 | - `LinkTo` is basic internal model to link to any Notion object
255 | - You can create object `LinkTo.create()` and use it in many places and methods
256 | - use `LinkTo(from_object=my_page1)` to quickly create a link to any existing object of pytion.models
257 | - `link` property of `LinkTo` returns expanded URL
258 | - `ElementArray` is found while using `.search()` endpoint. It's a parent of `PageArray`
259 |
260 | > And every model has a `.get()` method that returns API friendly JSON.
261 |
262 | ### Supported Property types
263 |
264 | | Property type | value type | read (DB) | read value (Page) | create (DB) | create value (Page) | Oper attrs | Config attrs |
265 | |--------------------------|----------------------------------|-----------|-------------------|-------------|---------------------|-------------------------------------|--------------------------------------------------------------------------------------------------------------|
266 | | `title` | `RichTextArray` | + | + | + | + | | |
267 | | `rich_text` | `RichTextArray` | + | + | + | + | | |
268 | | `number` | `int`/`float` | + | + | + | + | | ~~format~~ |
269 | | `select` | `str` | + | + | + | + | | ~~options~~ |
270 | | `multi_select` | `List[str]` | + | + | + | + | | ~~options~~ |
271 | | `status` | `str` | + | + | + | +\*\*\*\* | | `options`, `groups` (read-only) |
272 | | `date` | `str` | + | + | + | + | `start: datetime` `end: datetime`\* | |
273 | | `people` | `List[User]` | + | + | + | +\*\* | | |
274 | | `files` | | + | - | + | - | | |
275 | | `checkbox` | `bool` | + | + | + | + | | |
276 | | `url` | `str` | + | + | + | + | | |
277 | | `email` | `str` | + | + | + | + | | |
278 | | `phone_number` | `str` | + | + | + | + | | |
279 | | `formula` | | - | + | - | n/a | | |
280 | | `relation` | `List[LinkTo]` | + | + | + | + | `has_more: bool` | `single_property` / `dual_property` |
281 | | `rollup` | depends on relation and function | + | + | + | n/a | ~~has_more~~\*\*\*\*\* | `function`, `relation_property_id` / `relation_property_name`, `rollup_property_id` / `rollup_property_name` |
282 | | `unique_id` | `int` | + | + | + | n/a | | `prefix` |
283 | | `created_time`\*\*\* | `datetime` | + | + | + | n/a | | |
284 | | `created_by`\*\*\* | `User` | + | + | + | n/a | | |
285 | | `last_edited_time`\*\*\* | `datetime` | + | + | + | n/a | | |
286 | | `last_edited_by`\*\*\* | `User` | + | + | + | n/a | | |
287 |
288 | > [\*] - Create examples:
289 | > `pv = PropertyValue.create(type_="date", value=datetime.now())`
290 | > `pv = PropertyValue.create(type_="date", date={"start": str(datetime(2022, 2, 1, 5)), "end": str(datetime.now())})`
291 | > [\*\*] - Create example:
292 | > `user = User.create('1d393ffb5efd4d09adfc2cb6738e4812')`
293 | > `pv = PropertyValue.create(type_="people", value=[user])`
294 | > [\*\*\*] - Every Base model like Page already has mandatory attributes created/last_edited returned by API
295 | > [\*\*\*\*] - Status type is not configurable. API doesn't support NEW options added via Property modify or updating a Page
296 | > [\*\*\*\*\*] - Notion API hasn't `has_more` attr. Only 25 references can be shown in the array
297 |
298 | More details and examples can be found in Database [section](#property-values)
299 |
300 | More details and examples can be found in Database [section](#property-values)
301 |
302 |
303 | ## Supported block types
304 |
305 | At present the API only supports the block types which are listed in the reference below. Any unsupported block types will continue to appear in the structure, but only contain a `type` set to `"unsupported"`.
306 | Colors are not yet supported.
307 |
308 | Every Block has mandatory attributes and extension attributes. There are mandatory:
309 |
310 | - `id: str` - UUID-64 without hyphens
311 | - `object: str` - always `"block"` (from API)
312 | - `created_time: datetime` - from API
313 | - `created_by: User` - from API
314 | - `last_edited_time: datetime` - from API
315 | - `last_edited_by: User` - from API
316 | - `type: str` - the type of block (from API)
317 | - `has_children: bool` - does the block have children blocks (from API)
318 | - `archived: bool` - does the block marked as deleted (from API)
319 | - `text: Union[str, RichTextArray]` - **main content**
320 | - `simple: str` - only simple text string (url expanded)
321 |
322 | Extension attributes are listed below in support matrix:
323 |
324 | | Block Type | Description | Read support | Create support | Can have children | Extension attributes |
325 | |----------------------|-------------------------------------------|--------------|----------------|-------------------|---------------------------------------------------|
326 | | `paragraph` | Simple Block with text | + | + | + | |
327 | | `heading_1` | Heading Block with text highest level | + | + | -/+\* | `is_toggleable: bool` |
328 | | `heading_2` | Heading Block with text medium level | + | + | -/+\* | `is_toggleable: bool` |
329 | | `heading_3` | Heading Block with text lowest level | + | + | -/+\* | `is_toggleable: bool` |
330 | | `bulleted_list_item` | Text Block with bullet | + | - | + | |
331 | | `numbered_list_item` | Text Block with number | + | - | + | |
332 | | `to_do` | Text Block with checkbox | + | + | + | `checked: bool` |
333 | | `toggle` | Text Block with toggle to children blocks | + | - | + | |
334 | | `code` | Text Block with code style | + | + | + | `language: str`, `caption: RichTextArray` |
335 | | `child_page` | Page inside | + | - | + | |
336 | | `child_database` | Database inside | + | - | + | |
337 | | `embed` | Embed online content | + | - | - | `caption: RichTextArray` |
338 | | `image` | Embed image content | + | - | - | `caption: RichTextArray`, `expiry_time: datetime` |
339 | | `video` | Embed video content | + | - | - | `caption: RichTextArray`, `expiry_time: datetime` |
340 | | `file` | Embed file content | + | - | - | `caption: RichTextArray`, `expiry_time: datetime` |
341 | | `pdf` | Embed pdf content | + | - | - | `caption: RichTextArray`, `expiry_time: datetime` |
342 | | `bookmark` | Block for URL Link | + | - | - | `caption: RichTextArray` |
343 | | `callout` | Highlighted footnote text Block | + | - | + | `icon: dict` |
344 | | `quote` | Text Block with quote style | + | - | + | |
345 | | `equation` | KaTeX compatible text Block | + | - | - | |
346 | | `divider` | Simple line to divide the page | + | - | - | |
347 | | `table_of_contents` | Block with content structure in the page | + | - | - | |
348 | | `column` | | - | - | + | |
349 | | `column_list` | | - | - | - | |
350 | | `link_preview` | Same as `bookmark` | + | - | - | |
351 | | `synced_block` | Block for synced content aka parent | + | - | + | `synced_from: LinkTo` |
352 | | `template` | Template Block title | + | - | + | |
353 | | `link_to_page` | Block with link to particular page `@...` | + | - | - | `link: LinkTo` |
354 | | `table` | Table Block with some attrs | + | - | + | `table_width: int` |
355 | | `table_row` | Children Blocks with table row content | + | - | - | |
356 | | `breadcrumb` | Empty Block actually | + | - | - | |
357 | | `unsupported` | Blocks unsupported by API | + | - | - | |
358 |
359 | > [\*] - `heading_X` blocks can have children if `is_toggleable` is True
360 |
361 | ### Block creating examples
362 |
363 | Create `paragraph` block object and add it to Notion:
364 |
365 | ```python
366 | from pytion.models import Block
367 | my_text_block = Block.create("Hello World!")
368 | my_text_block = Block.create(text="Hello World!", type_="paragraph") # the same
369 |
370 | # indented append my block to other known block:
371 | no.blocks.block_append("5f60073a9dda4a9c93a212a74a107359", block=my_text_block)
372 |
373 | # append my block to a known page (in the end)
374 | no.blocks.block_append("9796f2525016128d9af4bf12b236b555", block=my_text_block) # the same operation actually
375 |
376 | # another way to append:
377 | my_page = no.pages.get("9796f2525016128d9af4bf12b236b555")
378 | my_page.block_append(block=my_text_block)
379 |
380 | # insert block after the existing block
381 | my_page.block_append(block=my_text_block, after="1496f2525016128d9af4bf12b236b000")
382 | # OR
383 | existing_block = no.blocks.get("1496f2525016128d9af4bf12b236b000")
384 | my_page.block_append(block=my_text_block, after=existing_block.obj)
385 | ```
386 |
387 | Create `to_do` block object:
388 |
389 | ```python
390 | from pytion.models import Block
391 | my_todo_block = Block.create("create readme documentation", type_="to_do")
392 | my_todo_block2 = Block.create("add 'create' method", type_="to_do", checked=True)
393 | ```
394 |
395 | Create `code` block object:
396 |
397 | ```python
398 | from pytion.models import Block
399 | my_code_block = Block.create("code example here", type_="code", language="javascript")
400 | my_code_block2 = Block.create("another code example", type_="code", caption="it will be plain text code block with caption")
401 | ```
402 |
403 | Create `heading` block object:
404 |
405 | ```python
406 | from pytion.models import Block
407 | my_code_block = Block.create("Title 1 example here", type_="heading_1")
408 | my_code_block2 = Block.create("Toggle Title 2", type_="heading_2", is_toggleable=True)
409 | ```
410 |
411 | ### Block deleting
412 |
413 | ```python
414 | no.blocks.block_update("3d4af9f0f98641dea8c44e3864eed4d0", archived=True)
415 | # or if you have Element with Block object already
416 | block.block_update(archived=True)
417 | ```
418 |
419 | ## Database operations
420 |
421 | ### Retrieving
422 |
423 | ```python
424 | from pytion import Notion
425 | no = Notion(token=TOKEN)
426 |
427 | # get all pages from Database
428 | # example 1
429 | pages = no.databases.db_query("114f1ef1f1241e2f12f41fe2f")
430 | # example 2
431 | db = no.databases.get("114f1ef1f1241e2f12f41fe2f")
432 | pages = db.db_query()
433 | print(pages.obj)
434 |
435 | # get pages with "task" in title
436 | pages = db.db_filter("task")
437 |
438 | # get all pages with sorting by property name "Tags"
439 | pages = db.db_filter("", ascending="Tags")
440 | pages = db.db_filter("", descending="Tags")
441 |
442 | # get pages with Status property equals Done
443 | pages = db.db_filter(property_name="Status", property_type="status", value="Done")
444 |
445 | # get pages with Price property greater than 150
446 | pages = db.db_filter(property_name="Price", property_type="number", condition="greater_than", value=150)
447 |
448 | # complex query
449 | pages = db.db_filter(
450 | property_name="WorkTime", property_type="date", condition="before",
451 | value=datetime.now(), descending="Deadline", limit=25
452 | )
453 |
454 | pages = db.db_filter(
455 | property_name="last_edited_time", property_type="timestamp", condition="on_or_after",
456 | value="2023-10-03", limit=1
457 | )
458 | ```
459 |
460 | > Queries with multifiltering and multisorting are not supported
461 | > But you can compose your custom filter dict from API reference and call `db.db_filter(raw={...})`
462 |
463 | Filter conditions and types combination -> [Official API reference](https://developers.notion.com/reference/post-database-query-filter)
464 |
465 | After you got `pages` which is `Element` object, you can not call API methods directly on `pages`
466 | because there is `PageArray` object with List of Pages.
467 | If you need to change a Page or something else, you can follow these steps:
468 |
469 | ```python
470 | # 1. create new Element object with non-list object type
471 | page = no.pages.from_object(pages.obj[14]) # choosed page from the PageArray
472 | # 2. call the desired API method on this page
473 | page.page_update(archived=True) # delete Page example
474 | ```
475 |
476 | ### Appending (creating a Page)
477 |
478 | There is a way to create a row into database. The same method is used to create any Page.
479 | The difference is in only in `parent` argument which can be the Page or the Database.
480 |
481 | ```python
482 | from pytion.models import LinkTo
483 |
484 | # choose the parent target
485 | # it can be the database
486 | parent = LinkTo.create(database_id="043cb52491a44b80a5e5006237a4278f")
487 | # or the page
488 | parent2 = LinkTo.create(page_id="043cb52491a44b80a5e5006237a4278f")
489 |
490 | # if you need to set Properties
491 | from pytion.models import PropertyValue
492 | props = {
493 | "Tags": PropertyValue.create(type_="multi_select", value=["tag1", "tag2"]),
494 | "done": PropertyValue.create("checkbox", True),
495 | "AnotherPropertyNAME": PropertyValue.create("date", datetime.now()),
496 | }
497 |
498 | # create the Page
499 | page = no.pages.page_create(parent=parent, title="Page 2") # without properties (will be empty)
500 | # or
501 | page2 = no.pages.page_create(parent=parent, properties=props, title="Page 2") # with properties
502 | ```
503 |
504 | ### Property Values
505 |
506 | Pytion Properties support table is described [above](#supported-property-types)
507 |
508 | There are Properties that are used in Database operations and PropertyValues that are used in Page operations.
509 |
510 | It's necessary to choose the type (`type_` arg) and value (`value`) of property.
511 | The table shows the mapping between Property type and value (python) type.
512 |
513 | The `type_` must correspond to your database schema in Notion.
514 |
515 | ```python
516 | from datetime import datetime
517 | from pytion.models import PropertyValue, LinkTo, RichTextArray, User
518 |
519 | # + relation type:
520 | pv = PropertyValue.create("relation", value=[LinkTo.create(page_id="04262843082a478d97f741948a32613b")])
521 | # + people type:
522 | pv = PropertyValue.create(type_="people", value=[User.create('1d393ffb5efd4d09adfc2cb6738e4812')])
523 | # + date type:
524 | pv = PropertyValue.create(type_="date", value=datetime.now())
525 | pv = PropertyValue.create(type_="date", date={"start": str(datetime(2022, 2, 1, 5)), "end": str(datetime.now())})
526 | # + rich_text (text or title field)
527 | pv = PropertyValue.create(type_="rich_text", value="Something Interesting")
528 | pv = PropertyValue.create("rich_text", value=RichTextArray.create("Something Interesting"))
529 | # + nubmer
530 | pv = PropertyValue.create(type_="number", value=156.2)
531 | # + status
532 | pv = PropertyValue.create("status", value="Done")
533 |
534 | # update needed property values
535 | new_props = {
536 | "Tags": PropertyValue.create("multi_select", ["tag2"]),
537 | "done": PropertyValue.create("checkbox", False),
538 | "when": PropertyValue.create("date", datetime.now()),
539 | }
540 | page = page_for_updates.page_update(properties=new_props)
541 | page = no.pages.page_update(page_for_updates_id, properties=new_props) # the same
542 |
543 | # rename (edit title property)
544 | page = page_for_updates.page_update(title=new_name)
545 | ```
546 |
547 | Pytion also provides the ways to change database schema - create/update/rename/delete properties:
548 |
549 | ```python
550 | from pytion.models import Property
551 |
552 | # rename property
553 | properties = {"Name": Property.create(type_="title", name="Subject")}
554 | database = database_for_updates.db_update(properties=properties)
555 | database = no.databases.db_update(database_for_updates_id, properties=properties) # the same
556 | # change property type
557 | properties = {"Tags": Property.create("select")}
558 | database = database_for_updates.db_update(properties=properties)
559 | # delete property from database
560 | properties = {"Old property name": Property.create(None)}
561 | database = database_for_updates.db_update(properties=properties)
562 | # rename database
563 | database = database_for_updates.db_update(title="Refactoring")
564 | ```
565 |
566 | # Logging
567 |
568 | Logging is muted by default. To enable to stdout and/or to file:
569 |
570 | ```python
571 | from pytion import setup_logging
572 |
573 | setup_logging(level="debug", to_console=True, filename="pytion.log")
574 | ```
575 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/pytion/models.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import annotations
3 | from datetime import datetime
4 | from typing import Optional, Dict, Union, List, Any
5 | from collections.abc import MutableSequence
6 |
7 | from pytion.envs import NOTION_URL
8 |
9 |
10 | # I wanna use pydantic, but API provide variable names of property
11 |
12 | class RichText(object):
13 | def __init__(self, **kwargs) -> None:
14 | self.plain_text: str = kwargs.get("plain_text")
15 | self.href: Optional[str] = kwargs.get("href")
16 | self.annotations: Dict[str, Union[bool, str]] = kwargs.get("annotations")
17 | # if not self.annotations:
18 | # self._create_default_annotations()
19 | self.type: str = kwargs.get("type")
20 | self.simple = ""
21 | if self.type == "mention":
22 | subtype = kwargs[self.type].get("type")
23 | if subtype == "user":
24 | self.data = User(**kwargs[self.type].get(subtype))
25 | self.plain_text = str(self.data)
26 | self.simple = LinkTo(from_object=self.data).link
27 | elif subtype == "page":
28 | sub_id = kwargs[self.type][subtype].get("id") if kwargs[self.type].get(subtype) else ""
29 | self.data = LinkTo.create(page=sub_id)
30 | if self.plain_text == "Untitled":
31 | self.plain_text = repr(self.data)
32 | else:
33 | self.plain_text = "LinkTo(" + self.plain_text + ")"
34 | self.simple = self.data.link
35 | elif subtype == "database":
36 | sub_id = kwargs[self.type][subtype].get("id") if kwargs[self.type].get(subtype) else ""
37 | self.data = LinkTo.create(database_id=sub_id)
38 | if self.plain_text == "Untitled":
39 | self.plain_text = repr(self.data)
40 | else:
41 | self.plain_text = "LinkTo(" + self.plain_text + ")"
42 | self.simple = self.data.link
43 | elif subtype == "date":
44 | self.data = {
45 | "start": Model.format_iso_time(kwargs[self.type][subtype].get("start")),
46 | "end": Model.format_iso_time(kwargs[self.type][subtype].get("end"))
47 | }
48 | self.simple = str(self.plain_text)
49 | elif subtype == "link_preview":
50 | self.simple = str(self.plain_text)
51 | self.plain_text = f"<{self.plain_text}>"
52 | self.data: Dict = kwargs[self.type]
53 | else:
54 | self.data: Dict = kwargs[self.type]
55 | self.simple = str(self.plain_text)
56 |
57 | def __str__(self):
58 | return str(self.plain_text)
59 |
60 | def __repr__(self):
61 | return f"RichText({self.plain_text})"
62 |
63 | def __bool__(self):
64 | return bool(self.plain_text)
65 |
66 | def _create_default_annotations(self):
67 | self.annotations = {
68 | "bold": False, "italic": False, "strikethrough": False,
69 | "underline": False, "code": False, "color": "default"
70 | }
71 |
72 | # def __len__(self):
73 | # return len(self.plain_text)
74 |
75 | def get(self) -> Dict[str, Any]:
76 | """
77 | Text type supported only
78 | """
79 | return {
80 | "type": "text",
81 | "text": {"content": self.plain_text, "link": None},
82 | # "annotations": self.annotations,
83 | # "plain_text": self.plain_text,
84 | }
85 |
86 |
87 | class RichTextArray(MutableSequence):
88 | def __init__(self, array: List[Dict]) -> None:
89 | self.array = [RichText(**rt) for rt in array]
90 |
91 | def __getitem__(self, item):
92 | return self.array[item]
93 |
94 | def __setitem__(self, key, value):
95 | self.array[key] = value
96 |
97 | def __delitem__(self, key):
98 | del self.array[key]
99 |
100 | def __len__(self):
101 | return len(self.array)
102 |
103 | def insert(self, index: int, value) -> None:
104 | self.array.insert(index, value)
105 |
106 | def __str__(self):
107 | return "".join(str(rt) for rt in self)
108 |
109 | def __repr__(self):
110 | return f"RichTextArray({str(self)})"
111 |
112 | def __bool__(self):
113 | return any(map(bool, self.array))
114 |
115 | def __add__(self, another: Union[RichTextArray, str]):
116 | if isinstance(another, str):
117 | another = RichTextArray.create(another)
118 | self.array.extend(another)
119 | return self
120 |
121 | def get(self) -> List[Dict[str, Any]]:
122 | return [item.get() for item in self]
123 |
124 | @classmethod
125 | def create(cls, text: str):
126 | return cls([{"type": "text", "plain_text": text, "text": {}}])
127 |
128 | @property
129 | def simple(self) -> str:
130 | return "".join(rt.simple for rt in self)
131 |
132 |
133 | class User(object):
134 | """
135 | The User object represents a user in a Notion workspace.
136 | """
137 | path = "users"
138 |
139 | def __init__(self, **kwargs) -> None:
140 | """
141 | Create an User object by providing dict from API.
142 |
143 | API attrs (from API docs):
144 | Mandatory:
145 | :param id: str
146 | :param object: str
147 |
148 | Optional:
149 | :param type: str
150 | :param name: str
151 | :param avatar_url: str
152 |
153 | Also Local attrs:
154 | :param raw: dict from API
155 | :param email: str if user is person
156 | """
157 | self.id = kwargs.get("id", "").replace("-", "")
158 | self.object = kwargs.get("object") # user
159 | self.type = kwargs.get("type")
160 | self.name = kwargs.get("name")
161 | self.avatar_url = kwargs.get("avatar_url")
162 | if self.type == "person" and kwargs.get(self.type):
163 | self.email = kwargs[self.type].get("email")
164 | self.workspace_name = None
165 | elif self.type == "bot":
166 | self.email = None
167 | self.workspace_name = kwargs[self.type].get("workspace_name")
168 | else:
169 | self.email = None
170 | self.workspace_name = None
171 | self.raw = kwargs
172 |
173 | def __str__(self):
174 | if self.name and self.email:
175 | name = f"{self.name}({self.email})"
176 | else:
177 | name = self.name
178 | return name if name else self.id
179 |
180 | def __repr__(self):
181 | return f"User({self})"
182 |
183 | def get(self) -> Dict[str, str]:
184 | return {
185 | "object": self.object,
186 | "id": self.id
187 | }
188 |
189 | @classmethod
190 | def create(cls, id: str):
191 | return cls(object="user", id=id)
192 |
193 |
194 | class Model(object):
195 | """
196 | :param id:
197 | :param object:
198 | :param created_time:
199 | :param last_edited_time:
200 | :param created_by:
201 | :param last_edited_by:
202 | :param raw:
203 | """
204 |
205 | def __init__(self, **kwargs) -> None:
206 | self.id = kwargs.get("id", "").replace("-", "")
207 | self.object = kwargs.get("object")
208 | self.created_time = self.format_iso_time(kwargs.get("created_time"))
209 | self.last_edited_time = self.format_iso_time(kwargs.get("last_edited_time"))
210 | self.created_by = User(**kwargs["created_by"]) if kwargs.get("created_by") else None
211 | self.last_edited_by = User(**kwargs["last_edited_by"]) if kwargs.get("last_edited_by") else None
212 | self.raw = kwargs
213 |
214 | @classmethod
215 | def format_iso_time(cls, time: str) -> Optional[datetime]:
216 | if not time:
217 | return None
218 | return datetime.fromisoformat(time.replace("Z", "+00:00"))
219 |
220 |
221 | class Property(object):
222 | def __init__(self, data: Dict[str, Any]):
223 | self.to_delete = True if data.get("type", False) is None else False
224 | self.id: str = data.get("id")
225 | self.type: str = data.get("type", "")
226 | self.name: str = data.get("name")
227 | self.raw = data
228 | self.subtype = None
229 |
230 | if self.type == "relation":
231 | if isinstance(data[self.type], dict):
232 | self.subtype = data[self.type].get("type")
233 | self.relation = LinkTo.create(database_id=data[self.type].get("database_id"))
234 | if self.subtype == "single_property":
235 | pass
236 | elif self.subtype == "dual_property":
237 | self.relation_property_id = data[self.type][self.subtype].get("synced_property_id")
238 | self.relation_property_name = data[self.type][self.subtype].get("synced_property_name")
239 |
240 | elif self.type == "status":
241 | if isinstance(data[self.type], dict):
242 | self.options = data[self.type].get("options", [])
243 | self.groups = data[self.type].get("groups", [])
244 |
245 | elif self.type == "rollup":
246 | if isinstance(data[self.type], dict):
247 | self.function = data[self.type].get("function")
248 | self.relation_property_id = data[self.type].get("relation_property_id")
249 | self.relation_property_name = data[self.type].get("relation_property_name")
250 | self.rollup_property_id = data[self.type].get("rollup_property_id")
251 | self.rollup_property_name = data[self.type].get("rollup_property_name")
252 |
253 | elif self.type == "unique_id":
254 | if isinstance(data[self.type], dict):
255 | self.prefix = data[self.type].get("prefix")
256 |
257 | def __str__(self):
258 | return self.name if self.name else self.type
259 |
260 | def __repr__(self):
261 | return f"Property({self})"
262 |
263 | def get(self) -> Optional[Dict[str, Dict]]:
264 | # property removing while patch
265 | if self.to_delete:
266 | return None
267 | # property renaming while patch
268 | data = {}
269 | if self.name:
270 | data["name"] = self.name
271 | # property retyping while patch
272 | if self.type:
273 | # create relation type property with configuration
274 | if self.type == "relation":
275 | data[self.type] = {self.subtype: {}, "database_id": self.relation.id}
276 | elif self.type == "status":
277 | data[self.type] = {}
278 | # not configurable by API
279 | # if self.options:
280 | # data[self.type]["options"] = self.options
281 | # if self.groups:
282 | # data[self.type]["groups"] = self.groups
283 | elif self.type == "rollup":
284 | data[self.type] = {"function": self.function}
285 | if self.relation_property_id:
286 | data[self.type]["relation_property_id"] = self.relation_property_id
287 | if self.relation_property_name:
288 | data[self.type]["relation_property_name"] = self.relation_property_name
289 | if self.rollup_property_id:
290 | data[self.type]["rollup_property_id"] = self.rollup_property_id
291 | if self.rollup_property_name:
292 | data[self.type]["rollup_property_name"] = self.rollup_property_name
293 | elif self.type == "unique_id":
294 | data[self.type] = {"prefix": self.prefix}
295 | else:
296 | data[self.type] = {}
297 | return data
298 |
299 | @classmethod
300 | def create(cls, type_: Optional[str] = "", **kwargs):
301 | """
302 | Property Schema Object (watch docs)
303 | :param type_: see "create (DB)" column in "Supported Property types" matrix of README
304 |
305 | + addons:
306 | set type_ = `None` to delete this Property
307 | set param `name` to rename this Property
308 |
309 | + relation type:
310 | set param `single_property` with `database_id` value OR
311 | set param `dual_property` with `database_id` value
312 | Property.create(type_="relation", dual_property="v111c132c12c1242341c41c")
313 |
314 | + rollup type:
315 | set param `function` from Nation API Rollup reference (BE AWARE ABOUT THE VALUE TYPE AND CHECK FUNCTION)
316 | set param `relation_property_id` with Property ID with Relation type OR \
317 | set param `relation_property_name` with Property NAME with Relation type
318 | set param `rollup_property_id` with Property ID of related database OR \
319 | set param `rollup_property_name` with Property NAME of related database
320 | Property.create("rollup", function="average", relation_property_id="GHpm", rollup_property_id="mvpx")
321 | """
322 | if type_ == "relation":
323 | subtype = next(kwarg for kwarg in kwargs if kwarg in ("single_property", "dual_property"))
324 | kwargs["relation"] = {"type": subtype, subtype: {}, "database_id": kwargs[subtype]}
325 | elif type_ == "status":
326 | kwargs["status"] = {}
327 | elif type_ == "rollup":
328 | kwargs["rollup"] = kwargs
329 | elif type_ == "unique_id":
330 | kwargs["unique_id"] = kwargs
331 | return cls({"type": type_, **kwargs})
332 |
333 |
334 | class PropertyValue(Property):
335 | def __init__(self, data: Dict, name: str, **kwargs):
336 | super().__init__(data)
337 | # getting Paginated Properties (for retrieving property item)
338 | # *Pagination
339 | if data.get("object") and data["object"] == "list":
340 | if data.get("results"):
341 | self.type = data["results"][0].get("type")
342 | data[self.type] = [sub_dict.get(sub_dict.get("type")) for sub_dict in data["results"]]
343 |
344 | self.name = name
345 | self.value = None
346 |
347 | if self.type in ["title", "rich_text"]:
348 | if isinstance(data[self.type], list):
349 | self.value = RichTextArray(data[self.type])
350 | elif isinstance(data[self.type], RichTextArray):
351 | self.value = data[self.type]
352 | else:
353 | self.value = RichTextArray.create(data[self.type])
354 |
355 | if self.type == "number":
356 | self.value: Union[int, float, None] = data["number"]
357 |
358 | if self.type == "select":
359 | if data["select"] and isinstance(data["select"], dict):
360 | self.value: Optional[str] = data["select"].get("name")
361 | elif data["select"] and isinstance(data["select"], str):
362 | self.value = data["select"]
363 | else:
364 | self.value = None
365 |
366 | if self.type == "multi_select":
367 | self.value: List[str] = [(v.get("name") if isinstance(v, dict) else v) for v in data["multi_select"]]
368 |
369 | if self.type == "checkbox":
370 | self.value: bool = data["checkbox"]
371 |
372 | if self.type == "date":
373 | if isinstance(data["date"], datetime):
374 | self.value = data["date"].isoformat()
375 | self.start = data["date"]
376 | self.end = None
377 | elif data["date"]:
378 | self.value: Optional[str] = data["date"].get("start")
379 | self.start: Optional[datetime] = Model.format_iso_time(data["date"].get("start"))
380 | self.end: Optional[datetime] = Model.format_iso_time(data["date"].get("end"))
381 | else:
382 | self.value = None
383 | self.start = None
384 | self.end = None
385 |
386 | if "time" in self.type:
387 | self.value: Optional[datetime] = Model.format_iso_time(data.get(self.type))
388 |
389 | if self.type == "formula":
390 | formula_type = data["formula"]["type"]
391 | if formula_type == "date":
392 | if data["formula"]["date"]:
393 | self.value: str = data["formula"]["date"].get("start")
394 | self.start: Optional[datetime] = Model.format_iso_time(data["formula"]["date"].get("start"))
395 | self.end: Optional[datetime] = Model.format_iso_time(data["formula"]["date"].get("end"))
396 | else:
397 | self.value = None
398 | self.start = None
399 | self.end = None
400 | else:
401 | self.value: Union[str, int, float, bool] = data["formula"][formula_type]
402 |
403 | if self.type == "created_by":
404 | self.value = User(**data.get(self.type))
405 |
406 | if self.type == "last_edited_by":
407 | self.value = User(**data.get(self.type))
408 |
409 | if self.type == "people":
410 | self.value = [user if isinstance(user, User) else User(**user) for user in data[self.type]]
411 |
412 | if self.type == "relation":
413 | self.value: List[LinkTo] = [
414 | LinkTo.create(page_id=item.get("id")) if not isinstance(item, LinkTo) else item
415 | for item in data[self.type]
416 | ]
417 | self.has_more = data["has_more"] if "has_more" in data else False
418 |
419 | if self.type == "status":
420 | self.value = data[self.type].get("name") if isinstance(data[self.type], dict) else data[self.type]
421 |
422 | if self.type == "rollup":
423 | rollup_type = data["rollup"]["type"]
424 | if rollup_type == "array":
425 | if len(data["rollup"]["array"]) == 0:
426 | self.value = None
427 | elif len(data["rollup"]["array"]) == 1:
428 | self.value = PropertyValue(data["rollup"]["array"][0], rollup_type)
429 | else:
430 | self.value = [PropertyValue(element, rollup_type).value for element in data["rollup"]["array"]]
431 |
432 | elif rollup_type == "number":
433 | self.value: Union[int, float, None] = data["rollup"]["number"]
434 |
435 | elif rollup_type == "date":
436 | if data["rollup"]["date"]:
437 | self.value: Optional[str] = data["rollup"]["date"].get("start")
438 | self.start: Optional[datetime] = Model.format_iso_time(data["rollup"]["date"].get("start"))
439 | self.end: Optional[datetime] = Model.format_iso_time(data["rollup"]["date"].get("end"))
440 | else:
441 | self.value = None
442 | self.start = None
443 | self.end = None
444 | else:
445 | self.value = "unsupported rollup type"
446 |
447 | if self.type == "files":
448 | self.value = "unsupported"
449 |
450 | if self.type == "url":
451 | self.value: Optional[str] = data.get("url")
452 |
453 | if self.type == "email":
454 | self.value: Optional[str] = data.get("email")
455 |
456 | if self.type == "phone_number":
457 | self.value: Optional[str] = data.get("phone_number")
458 |
459 | if self.type == "unique_id":
460 | self.value: int = data["unique_id"]["number"] if "number" in data["unique_id"] else 0
461 |
462 | def __str__(self):
463 | return str(self.value)
464 |
465 | def __repr__(self):
466 | return f"{self.name}({self})"
467 |
468 | def get(self):
469 | # checkbox can not be `None`
470 | if self.type in ["checkbox"]:
471 | return {self.type: self.value}
472 |
473 | # empty values
474 | elif not self.value:
475 | if self.type in ["multi_select", "relation", "rich_text", "people", "files"]:
476 | return {self.type: []}
477 | return {self.type: None}
478 |
479 | # RichTextArray
480 | elif self.type in ["title", "rich_text"] and hasattr(self.value, "get"):
481 | return {self.type: self.value.get()}
482 |
483 | # simple values
484 | elif self.type in ["number", "url", "email", "phone_number"]:
485 | return {self.type: self.value}
486 |
487 | # select type
488 | elif self.type == "select":
489 | return {self.type: {"name": self.value}}
490 |
491 | # multi-select type
492 | elif self.type == "multi_select":
493 | return {self.type: [{"name": tag} for tag in self.value]}
494 |
495 | # date type
496 | elif self.type == "date" and hasattr(self, "start") and hasattr(self, "end"):
497 | with_time = True if self.start.hour or self.start.minute else False
498 | if self.start:
499 | start = self.start.astimezone().isoformat() if with_time else str(self.start.date())
500 | else:
501 | start = None
502 | if self.end:
503 | end = self.end.astimezone().isoformat() if with_time else str(self.end.date())
504 | else:
505 | end = None
506 | return {self.type: {"start": start, "end": end}}
507 |
508 | # people type
509 | elif self.type == "people":
510 | return {self.type: [user.get() for user in self.value]}
511 |
512 | # relation type
513 | elif self.type == "relation":
514 | return {self.type: [{"id": lt.id} for lt in self.value]}
515 |
516 | # status type
517 | elif self.type == "status":
518 | return {self.type: {"name": self.value}}
519 |
520 | # unsupported types:
521 | elif self.type in ["files"]:
522 | return {self.type: []}
523 | elif self.type in ["created_time", "last_edited_by", "last_edited_time", "created_by"]:
524 | return None
525 | elif self.type in ["formula", "rollup", "unique_id"]:
526 | return {self.type: {}}
527 | return None
528 |
529 | @classmethod
530 | def create(cls, type_: str = "", value: Any = None, **kwargs):
531 | """
532 | PropertyValue Schema Object (watch docs)
533 | :param type_: see "create value (Page)" column in "Supported Property types" matrix of README
534 | :param value: see "value type" column in "Supported Property types" matrix of README
535 |
536 | ~ examples:
537 | + relation type:
538 | pv = PropertyValue.create("relation", value=[LinkTo.create(page_id="04262843082a478d97f741948a32613b")])
539 | + people type:
540 | pv = PropertyValue.create(type_="people", value=[User.create('1d393ffb5efd4d09adfc2cb6738e4812')])
541 | + date type:
542 | pv = PropertyValue.create(type_="date", value=datetime.now())
543 | pv = PropertyValue.create(type_="date", date={"start": str(datetime(2022, 2, 1, 5)), "end": str(datetime.now())})
544 | """
545 | return cls({"type": type_, type_: value, **kwargs}, name="")
546 |
547 |
548 | class Database(Model):
549 | object = "database"
550 | path = "databases"
551 |
552 | def __init__(self, **kwargs) -> None:
553 | """
554 | params from Model +
555 | :param cover:
556 | :param icon:
557 | :param title:
558 | :param properties:
559 | :param parent:
560 | :param url:
561 | :param is_inline:
562 | """
563 | super().__init__(**kwargs)
564 | self.cover: Optional[Dict] = kwargs.get("cover")
565 | self.icon: Optional[Dict] = kwargs.get("icon")
566 | self.title = (kwargs.get("title")
567 | if isinstance(kwargs["title"], RichTextArray) or not kwargs.get("title")
568 | else RichTextArray(kwargs["title"])
569 | )
570 | self.properties = {
571 | name: (value if isinstance(value, Property) else Property(value))
572 | for name, value in kwargs["properties"].items()
573 | }
574 | self.parent = kwargs["parent"] if isinstance(kwargs.get("parent"), LinkTo) else LinkTo(**kwargs["parent"])
575 | self.url: str = kwargs.get("url")
576 | self.public_url = kwargs.get("public_url")
577 | self.description = None
578 | if "description" in kwargs and kwargs["description"]:
579 | if isinstance(kwargs["description"], RichTextArray):
580 | self.description = kwargs["description"]
581 | elif isinstance(kwargs["description"], str):
582 | self.description = RichTextArray.create(kwargs["description"])
583 | else:
584 | self.description = RichTextArray(kwargs["description"])
585 | self.is_inline: bool = kwargs.get("is_inline")
586 |
587 | def __str__(self):
588 | return str(self.title)
589 |
590 | def __repr__(self):
591 | return f"Database({self.title})"
592 |
593 | def get(self) -> Dict[str, Dict]:
594 | new_dict = {
595 | "parent": self.parent.get(),
596 | "properties": {name: value.get() for name, value in self.properties.items()}
597 | }
598 | if isinstance(self.title, RichTextArray):
599 | new_dict["title"] = self.title.get()
600 | if self.description:
601 | new_dict["description"] = self.description.get()
602 | return new_dict
603 |
604 | @classmethod
605 | def create(cls, parent: LinkTo, properties: Dict[str, Property], title: Optional[RichTextArray] = None, **kwargs):
606 | return cls(parent=parent, properties=properties, title=title, **kwargs)
607 |
608 |
609 | class Page(Model):
610 | object = "page"
611 | path = "pages"
612 |
613 | def __init__(self, **kwargs) -> None:
614 | """
615 | params from Model +
616 | :param cover:
617 | :param icon:
618 | :param parent:
619 | :param archived:
620 | :param properties:
621 | :param url:
622 | """
623 | super().__init__(**kwargs)
624 | self.cover: Optional[Dict] = kwargs.get("cover")
625 | self.icon: Optional[Dict] = kwargs.get("icon")
626 | self.parent = kwargs["parent"] if isinstance(kwargs.get("parent"), LinkTo) else LinkTo(**kwargs["parent"])
627 | self.archived: bool = kwargs.get("archived")
628 | self.url: str = kwargs.get("url")
629 | self.public_url = kwargs.get("public_url")
630 | self.children = kwargs["children"] if "children" in kwargs else LinkTo(block=self)
631 | self.properties = {
632 | name: (PropertyValue(data, name) if not isinstance(data, PropertyValue) else data)
633 | for name, data in kwargs["properties"].items()
634 | }
635 | for p in self.properties.values():
636 | if "title" in p.type:
637 | self.title = p.value
638 | break
639 | else:
640 | self.title = None
641 |
642 | def __str__(self):
643 | return str(self.title)
644 |
645 | def __repr__(self):
646 | return f"Page({self.title})"
647 |
648 | def get(self):
649 | new_dict = {
650 | "parent": self.parent.get(without_type=True),
651 | "icon": self.icon, # optional
652 | "cover": self.cover, # optional
653 | "properties": {name: p.get() for name, p in self.properties.items()},
654 | }
655 | if getattr(self, "children", None):
656 | new_dict["children"] = self.children.get() # can not be None
657 | return new_dict
658 |
659 | @classmethod
660 | def create(
661 | cls, parent: LinkTo, properties: Optional[Dict[str, PropertyValue]] = None,
662 | title: Union[RichTextArray, str, None] = None, children: Optional[BlockArray] = None, **kwargs
663 | ):
664 | if not properties:
665 | properties = {}
666 | if title:
667 | properties["title"] = PropertyValue.create("title", title)
668 | return cls(parent=parent, properties=properties, children=children, **kwargs)
669 |
670 |
671 | class Block(Model):
672 | object = "block"
673 | path = "blocks"
674 |
675 | def __init__(self, **kwargs):
676 | """
677 | params from Model +
678 | :param has_children:
679 | :param type:
680 | :param archived:
681 | :param create_mode:
682 | """
683 | super().__init__(**kwargs)
684 | self.type: str = kwargs.get("type")
685 | self.has_children: bool = kwargs.get("has_children")
686 | self.archived: bool = kwargs.get("archived")
687 | self.children = LinkTo(block=self)
688 | self._level = kwargs["level"] if kwargs.get("level") else 0
689 | self.create_mode: bool = kwargs["create_mode"] if "create_mode" in kwargs else False
690 | self.parent = None
691 | self._plain_text = ""
692 |
693 | if self.create_mode:
694 | self.text = kwargs[self.type]
695 | if "checked" in kwargs:
696 | self.checked = kwargs["checked"]
697 | if "language" in kwargs:
698 | self.language = kwargs["language"]
699 | if "caption" in kwargs:
700 | self.caption = kwargs["caption"]
701 | if isinstance(self.caption, str):
702 | self.caption = RichTextArray.create(self.caption)
703 | if "is_toggleable" in kwargs:
704 | self.is_toggleable = kwargs["is_toggleable"]
705 | return
706 | self.parent = kwargs["parent"] if isinstance(kwargs.get("parent"), LinkTo) else LinkTo(**kwargs["parent"])
707 |
708 | if self.type == "paragraph":
709 | self.text = RichTextArray(kwargs[self.type].get("rich_text"))
710 | self._plain_text = self.text.simple
711 |
712 | elif "heading" in self.type:
713 | indent = self.type.split("_")[-1]
714 | indent_num = int(indent) if indent.isdigit() else 0
715 | prefix = "#" * indent_num + " "
716 | r_text = RichTextArray(kwargs[self.type].get("rich_text"))
717 | self.text = RichTextArray.create(prefix) + r_text
718 | self._plain_text = r_text.simple
719 | self.is_toggleable: bool = kwargs[self.type].get("is_toggleable")
720 |
721 | elif self.type == "callout":
722 | self.text = RichTextArray(kwargs[self.type].get("rich_text"))
723 | self._plain_text = self.text.simple
724 | self.icon: Dict = kwargs[self.type].get("icon")
725 |
726 | elif self.type == "quote":
727 | r_text = RichTextArray(kwargs[self.type].get("rich_text"))
728 | self.text = RichTextArray.create("| ") + r_text
729 | self._plain_text = r_text.simple
730 |
731 | elif "list_item" in self.type:
732 | r_text = RichTextArray(kwargs[self.type].get("rich_text"))
733 | self.text = RichTextArray.create("- ") + r_text
734 | self._plain_text = r_text.simple
735 | # Numbers does not support cause of lack of relativity
736 |
737 | elif self.type == "to_do":
738 | self.checked: bool = kwargs[self.type].get("checked")
739 | prefix = "[x] " if self.checked else "[ ] "
740 | r_text = RichTextArray(kwargs[self.type].get("rich_text"))
741 | self.text = RichTextArray.create(prefix) + r_text
742 | self._plain_text = r_text.simple
743 |
744 | elif self.type == "toggle":
745 | r_text = RichTextArray(kwargs[self.type].get("rich_text"))
746 | self.text = RichTextArray.create("> ") + r_text
747 | self._plain_text = r_text.simple
748 |
749 | elif self.type == "code":
750 | r_text = RichTextArray(kwargs[self.type].get("rich_text"))
751 | self.language: str = kwargs[self.type].get("language")
752 | prefix = RichTextArray.create(f"```{self.language}\n") if self.language else RichTextArray.create("```\n")
753 | self.text = prefix + r_text + "\n```"
754 | self._plain_text = r_text.simple
755 | self.caption = RichTextArray(kwargs[self.type].get("caption"))
756 |
757 | # when the block is child_page, parent will be the page object
758 | # when the block is child_database, parent AND children will be the database object
759 | elif "child" in self.type:
760 | self.text: str = kwargs[self.type].get("title")
761 | self._plain_text = str(self.text)
762 | if self.type == "child_page":
763 | # self.children is already set
764 | self.parent = LinkTo(type="page", page=self.id)
765 | self._plain_text = str(self.parent.link)
766 | elif self.type == "child_database":
767 | # well yes. parent and children are the same. parent of this database will be the page of this block
768 | # and the database is children of this block
769 | self.parent = LinkTo.create(database_id=self.id)
770 | self.children = LinkTo.create(database_id=self.id)
771 | self._plain_text = str(self.parent.link)
772 | if not self.text:
773 | self.text = repr(self.children)
774 | # page self.has_children is correct. checked.
775 | # database self.has_children is false.
776 | # database with custom source had no title!
777 |
778 | # hello, markdown
779 | elif self.type == "embed":
780 | self.caption = RichTextArray(kwargs[self.type].get("caption"))
781 | text = kwargs[self.type].get("url")
782 | self._plain_text = str(text)
783 | if self.caption:
784 | self.text = f'[{self.caption}]({text})'
785 | else:
786 | self.text = f'<{text}>' if text else "*Empty embed*"
787 |
788 | elif self.type == "image":
789 | self.caption = RichTextArray(kwargs[self.type].get("caption"))
790 | subtype = kwargs[self.type].get("type")
791 | if subtype == "file":
792 | # The file S3 URL will be valid for 1 hour
793 | self.expiry_time = Model.format_iso_time(kwargs[self.type][subtype].get("expiry_time"))
794 | else:
795 | self.expiry_time = None
796 | if subtype in ("file", "external"):
797 | text = kwargs[self.type][subtype].get("url")
798 | self._plain_text = str(text)
799 | if self.caption:
800 | self.text = f'[{self.caption}]({text})'
801 | else:
802 | self.text = f'<{text}>'
803 | else:
804 | self.text = "*Unknown image type*"
805 | self._plain_text = "None"
806 |
807 | elif self.type == "video":
808 | self.caption = RichTextArray(kwargs[self.type].get("caption"))
809 | subtype = kwargs[self.type].get("type")
810 | if subtype == "file":
811 | self.expiry_time = Model.format_iso_time(kwargs[self.type][subtype].get("expiry_time"))
812 | else:
813 | self.expiry_time = None
814 | if subtype in ("file", "external"):
815 | text = kwargs[self.type][subtype].get("url")
816 | self._plain_text = str(text)
817 | if self.caption:
818 | self.text = f'[{self.caption}]({text})'
819 | else:
820 | self.text = f'<{text}>'
821 | else:
822 | self.text = "*Unknown video type*"
823 | self._plain_text = "None"
824 |
825 | elif self.type == "file":
826 | self.caption = RichTextArray(kwargs[self.type].get("caption"))
827 | subtype = kwargs[self.type].get("type")
828 | if subtype == "file":
829 | self.expiry_time = Model.format_iso_time(kwargs[self.type][subtype].get("expiry_time"))
830 | else:
831 | self.expiry_time = None
832 | if subtype in ("file", "external"):
833 | text = kwargs[self.type][subtype].get("url")
834 | self._plain_text = str(text)
835 | if self.caption:
836 | self.text = f'[{self.caption}]({text})'
837 | else:
838 | self.text = f'<{text}>'
839 | else:
840 | self.text = "*Unknown file type*"
841 | self._plain_text = "None"
842 |
843 | elif self.type == "pdf":
844 | self.caption = RichTextArray(kwargs[self.type].get("caption"))
845 | subtype = kwargs[self.type].get("type")
846 | if subtype == "file":
847 | self.expiry_time = Model.format_iso_time(kwargs[self.type][subtype].get("expiry_time"))
848 | else:
849 | self.expiry_time = None
850 | if subtype in ("file", "external"):
851 | text = kwargs[self.type][subtype].get("url")
852 | self._plain_text = str(text)
853 | if self.caption:
854 | self.text = f'[{self.caption}]({text})'
855 | else:
856 | self.text = f'<{text}>'
857 | else:
858 | self.text = "*Unknown pdf type*"
859 | self._plain_text = "None"
860 |
861 | elif self.type == "breadcrumb":
862 | self.text = "*breadcrumb block*"
863 | self._plain_text = "None"
864 |
865 | elif self.type == "bookmark":
866 | self.caption = RichTextArray(kwargs[self.type].get("caption"))
867 | text = kwargs[self.type].get("url")
868 | self._plain_text = str(text)
869 | if self.caption:
870 | self.text = f'[{self.caption}]({text})'
871 | else:
872 | self.text = f'<{text}>' if text else "*Empty bookmark*"
873 |
874 | elif self.type == "link_preview":
875 | text = kwargs[self.type].get("url")
876 | self._plain_text = str(text)
877 | self.text = f'<{text}>'
878 |
879 | elif self.type == "link_to_page":
880 | self.link = LinkTo(**kwargs[self.type])
881 | self.text = repr(self.link)
882 | self._plain_text = str(self.link.link)
883 |
884 | elif self.type == "equation":
885 | self.text: str = kwargs[self.type].get("expression")
886 | self._plain_text = str(self.text)
887 |
888 | elif self.type == "divider":
889 | self.text = "---"
890 | self._plain_text = "None"
891 |
892 | elif self.type == "table_of_contents":
893 | self.text = "*Table of contents*"
894 | self._plain_text = "None"
895 |
896 | elif self.type == "template":
897 | r_text = RichTextArray(kwargs[self.type].get("rich_text"))
898 | self.text = RichTextArray.create("Template: ") + r_text
899 | self._plain_text = r_text.simple
900 |
901 | elif self.type == "synced_block":
902 | synced_from = kwargs[self.type].get("synced_from")
903 | self.text = "*SYNCED BLOCK:*"
904 | self._plain_text = "None"
905 | self.synced_from = LinkTo(**synced_from) if synced_from else None
906 |
907 | elif self.type == "table":
908 | self.table_width: int = kwargs[self.type].get("table_width")
909 | self.text = f"*Table {self.table_width}xN:*"
910 | self._plain_text = "None"
911 |
912 | elif self.type == "table_row":
913 | cells = kwargs[self.type].get("cells")
914 | self.text = RichTextArray.create("| ")
915 | for cell in cells:
916 | text_cell = RichTextArray(cell)
917 | self._plain_text += f"\"{text_cell}\","
918 | self.text += text_cell + " | "
919 | self._plain_text = self._plain_text.strip(",")
920 |
921 | elif self.type == "unsupported":
922 | self.text = "*****"
923 | self._plain_text = "None"
924 |
925 | else:
926 | self.text = "*UNKNOWN_BLOCK_TYPE*"
927 | self._plain_text = "None"
928 |
929 | def __str__(self):
930 | return str(self.text)
931 |
932 | def __repr__(self):
933 | return f"Block({str(self.text)[:30]})"
934 |
935 | def get(self, with_object_type: bool = False):
936 | if self.type in [
937 | "paragraph", "quote", "heading_1", "heading_2", "heading_3", "to_do",
938 | "bulleted_list_item", "numbered_list_item", "toggle", "callout", "code", "child_database"
939 | ]:
940 |
941 | text = RichTextArray.create(self.text) if isinstance(self.text, str) else self.text
942 |
943 | # base content
944 | new_dict = {self.type: {"rich_text": text.get()}}
945 |
946 | # to_do type attrs
947 | if self.type == "to_do" and hasattr(self, "checked"):
948 | new_dict[self.type]["checked"] = self.checked
949 |
950 | # code type attrs
951 | elif self.type == "code":
952 | new_dict[self.type]["language"] = getattr(self, "language", "plain text")
953 | if hasattr(self, "caption"):
954 | new_dict[self.type]["caption"] = self.caption.get()
955 |
956 | # child_database type struct
957 | elif self.type == "child_database":
958 | new_dict = {self.type: {"title": str(text)}}
959 |
960 | # heading_X types attrs
961 | elif "heading" in self.type:
962 | if hasattr(self, "is_toggleable") and isinstance(self.is_toggleable, bool):
963 | new_dict[self.type]["is_toggleable"] = self.is_toggleable
964 | else:
965 | new_dict[self.type]["is_toggleable"] = False
966 |
967 | if with_object_type:
968 | new_dict["object"] = "block"
969 | new_dict["type"] = self.type
970 | return new_dict
971 | return None
972 |
973 | @property
974 | def simple(self) -> str:
975 | if self._plain_text:
976 | return self._plain_text if self._plain_text != "None" else ""
977 | if getattr(self, "text", None):
978 | return str(self.text)
979 | return self._plain_text
980 |
981 | @classmethod
982 | def create(cls, text: str, type_: str = "paragraph", **kwargs):
983 | """
984 | :param text: Block content
985 | :param type_: Block types (API)
986 | :param kwargs:
987 | :kwargs param checked: bool for to_do
988 | :kwargs param language: str for code
989 | :kwargs param caption: str or RichTextArray for code
990 | :kwargs param is_toggleable: bool for heading_1, heading_2, heading_3
991 | :return:
992 | """
993 | new_dict = {
994 | "type": type_,
995 | type_: text,
996 | }
997 | return cls(**new_dict, create_mode=True, **kwargs)
998 |
999 |
1000 | class ElementArray(MutableSequence):
1001 | class_map = {"page": Page, "database": Database, "block": Block}
1002 |
1003 | def __init__(self, array, create: bool = False):
1004 | if create:
1005 | self.array = array
1006 | return
1007 |
1008 | self.array = []
1009 | for ele in array:
1010 | if ele.get("object") and ele["object"] in self.class_map:
1011 | self.array.append(self.class_map[ele["object"]](**ele))
1012 |
1013 | def __getitem__(self, item):
1014 | return self.array[item]
1015 |
1016 | def __setitem__(self, key, value):
1017 | self.array[key] = value
1018 |
1019 | def __delitem__(self, key):
1020 | del self.array[key]
1021 |
1022 | def __len__(self):
1023 | return len(self.array)
1024 |
1025 | def insert(self, index: int, value) -> None:
1026 | self.array.insert(index, value)
1027 |
1028 | def __str__(self):
1029 | return "\n".join(str(b) for b in self)
1030 |
1031 | def __repr__(self):
1032 | r = str(self)[:30].replace("\n", " ")
1033 | return f"ElementArray({r})"
1034 |
1035 |
1036 | class BlockArray(ElementArray):
1037 | def __str__(self):
1038 | return "\n".join(b._level * "\t" + str(b) for b in self)
1039 |
1040 | def __repr__(self):
1041 | r = str(self)[:30].replace("\n", " ")
1042 | return f"BlockArray({r})"
1043 |
1044 | def get(self):
1045 | return [b.get() for b in self]
1046 |
1047 | @property
1048 | def simple(self) -> str:
1049 | return "\n".join(b._level * "\t" + b.simple for b in self)
1050 |
1051 |
1052 | class PageArray(ElementArray):
1053 | def __repr__(self):
1054 | r = str(self)[:30].replace("\n", " ")
1055 | return f"PageArray({r})"
1056 |
1057 |
1058 | class LinkTo(object):
1059 | """
1060 | schema
1061 | .type = `element_type`
1062 | .id = `elementID`
1063 |
1064 | .get() - return API like style
1065 | .create() - create in format `(page_id="123412341234")` or (database_id="13412341234")`
1066 | """
1067 |
1068 | def __init__(
1069 | self, block: Optional[Model] = None, from_object: Union[Block, Page, Database, None] = None, **kwargs
1070 | ):
1071 | """
1072 | Creates LinkTo object from API dict
1073 |
1074 | :param block: Block object can be provided instead other attrs. Internal usage.
1075 | :param from_object: Any model object can be provided to create LinkTo to it.
1076 | :param kwargs: API attrs. Internal usage.
1077 | """
1078 | if block:
1079 | self.type = block.object
1080 | self.id = block.id
1081 | self.after_path = "children"
1082 | self.uri = "blocks"
1083 | # You can provide the object to create the LinkTo to it
1084 | elif from_object:
1085 | self.uri = from_object.path
1086 | self.id = from_object.id
1087 | if isinstance(from_object, Page):
1088 | self.type = "page_id"
1089 | elif isinstance(from_object, Database):
1090 | self.type = "database_id"
1091 | elif isinstance(from_object, Block):
1092 | self.type = "block_id"
1093 | elif isinstance(from_object, User):
1094 | self.type = "user_id"
1095 | else:
1096 | self.type: str = kwargs.get("type")
1097 | self.id: str = kwargs.get(self.type) if kwargs.get(self.type) else kwargs.get("id")
1098 | if self.type == "workspace":
1099 | self.id = ""
1100 | self.after_path = ""
1101 | if self.type == "page_id":
1102 | self.uri = "pages"
1103 | elif self.type == "database_id":
1104 | self.uri = "databases"
1105 | # when type is set manually
1106 | elif self.type == "page": # deprecated.
1107 | self.uri = "pages"
1108 | elif self.type == "block_id":
1109 | self.uri = "blocks"
1110 | elif self.type == "user_id":
1111 | self.uri = "users"
1112 | else:
1113 | self.uri = None
1114 |
1115 | if isinstance(self.id, str):
1116 | self.id = self.id.replace("-", "")
1117 |
1118 | def __str__(self):
1119 | prefix = self.uri if self.uri else self.type
1120 | if getattr(self, "after_path", ""):
1121 | return f"{prefix}/{self.id}/{self.after_path}"
1122 | return f"{prefix}/{self.id}"
1123 |
1124 | def __repr__(self):
1125 | return f"LinkTo({self})"
1126 |
1127 | @property
1128 | def link(self) -> str:
1129 | return NOTION_URL + str(self)
1130 |
1131 | def get(self, without_type: bool = False):
1132 | if self.type == "workspace":
1133 | return {"type": "workspace", "workspace": True}
1134 | if without_type:
1135 | return {self.type: self.id}
1136 | return {"type": self.type, self.type: self.id}
1137 |
1138 | @classmethod
1139 | def create(cls, **kwargs):
1140 | """
1141 | `.create(page_id="123412341234")`
1142 | `.create(database_id="13412341234")`
1143 | `.create(workspace=True)`
1144 | """
1145 | for key, value in kwargs.items():
1146 | return cls(type=key, id=value)
1147 |
--------------------------------------------------------------------------------