|
| 1 | +from typing import Any, Dict, Generator, List, Optional, TYPE_CHECKING |
| 2 | + |
| 3 | +from pydantic.v1 import BaseModel |
| 4 | + |
| 5 | +from python_notion_api.async_api.notion_page import NotionPage |
| 6 | +from python_notion_api.async_api.utils import ensure_loaded |
| 7 | +from python_notion_api.models.common import FileObject, ParentObject |
| 8 | +from python_notion_api.models.configurations import ( |
| 9 | + NotionPropertyConfiguration, |
| 10 | + RelationPropertyConfiguration, |
| 11 | +) |
| 12 | +from python_notion_api.models.filters import FilterItem |
| 13 | +from python_notion_api.models.objects import DataSource |
| 14 | +from python_notion_api.models.sorts import Sort |
| 15 | +from python_notion_api.models.values import PropertyValue, generate_value |
| 16 | + |
| 17 | +if TYPE_CHECKING: |
| 18 | + from python_notion_api.async_api.api import AsyncNotionAPI |
| 19 | + |
| 20 | + |
| 21 | +class NotionDataSource: |
| 22 | + """Wrapper for a Notion datasource object. |
| 23 | +
|
| 24 | + Args: |
| 25 | + api: Instance of the NotionAPI. |
| 26 | + data_source_id: Id of the data source. |
| 27 | + """ |
| 28 | + |
| 29 | + class CreatePageRequest(BaseModel): |
| 30 | + parent: ParentObject |
| 31 | + properties: Dict[str, PropertyValue] |
| 32 | + cover: Optional[FileObject] |
| 33 | + |
| 34 | + def __init__(self, api: "AsyncNotionAPI", data_source_id: str): |
| 35 | + self._api = api |
| 36 | + self._data_source_id = data_source_id |
| 37 | + self._object = None |
| 38 | + self._properties = None |
| 39 | + self._title = None |
| 40 | + |
| 41 | + @ensure_loaded |
| 42 | + def __getattr__(self, attr_key): |
| 43 | + return getattr(self._object, attr_key) |
| 44 | + |
| 45 | + @property |
| 46 | + def data_source_id(self) -> str: |
| 47 | + return self._data_source_id.replace("-", "") |
| 48 | + |
| 49 | + async def reload(self): |
| 50 | + self._object = await self._api._get( |
| 51 | + endpoint=f"data_sources/{self._data_source_id}", |
| 52 | + cast_cls=DataSource, |
| 53 | + ) |
| 54 | + |
| 55 | + if self._object is None: |
| 56 | + raise Exception( |
| 57 | + f"Error loading data source {self._data_source_id}" |
| 58 | + ) |
| 59 | + |
| 60 | + self._properties = { |
| 61 | + key: NotionPropertyConfiguration.from_obj(val) |
| 62 | + for key, val in self._object.properties.items() |
| 63 | + } |
| 64 | + self._title = "".join(rt.plain_text for rt in self._object.title) |
| 65 | + |
| 66 | + async def query( |
| 67 | + self, |
| 68 | + filters: Optional[FilterItem] = None, |
| 69 | + sorts: Optional[List[Sort]] = None, |
| 70 | + page_limit: Optional[int] = None, |
| 71 | + cast_cls=NotionPage, |
| 72 | + ) -> Generator[NotionPage, None, None]: |
| 73 | + """A wrapper for 'Query a data source' action. |
| 74 | +
|
| 75 | + Retrieves all pages belonging to the data source. |
| 76 | +
|
| 77 | + Args: |
| 78 | + filters: |
| 79 | + sorts: |
| 80 | + cast_cls: A subclass of a NotionPage. Allows custom |
| 81 | + property retrieval |
| 82 | +
|
| 83 | + """ |
| 84 | + data = {} |
| 85 | + if filters is not None: |
| 86 | + filters = filters.dict(by_alias=True, exclude_unset=True) |
| 87 | + data["filter"] = filters |
| 88 | + |
| 89 | + if sorts is not None: |
| 90 | + data["sorts"] = [ |
| 91 | + sort.dict(by_alias=True, exclude_unset=True) for sort in sorts |
| 92 | + ] |
| 93 | + |
| 94 | + async for item in self._api._post_iterate( |
| 95 | + endpoint=f"data_sources/{self._data_source_id}/query", |
| 96 | + data=data, |
| 97 | + page_limit=page_limit, |
| 98 | + ): |
| 99 | + yield cast_cls( |
| 100 | + api=self._api, data_source=self, page_id=item.page_id, obj=item |
| 101 | + ) |
| 102 | + |
| 103 | + @property |
| 104 | + @ensure_loaded |
| 105 | + def title(self) -> str: |
| 106 | + """Get the title of the data source.""" |
| 107 | + return self._title |
| 108 | + |
| 109 | + @property |
| 110 | + @ensure_loaded |
| 111 | + def properties(self) -> Dict[str, NotionPropertyConfiguration]: |
| 112 | + """Get all property configurations of the data source.""" |
| 113 | + return self._properties |
| 114 | + |
| 115 | + @property |
| 116 | + @ensure_loaded |
| 117 | + def relations(self) -> Dict[str, RelationPropertyConfiguration]: |
| 118 | + """Get all property configurations of the data source that are |
| 119 | + relations. |
| 120 | + """ |
| 121 | + return { |
| 122 | + key: val |
| 123 | + for key, val in self._properties.items() |
| 124 | + if isinstance(val, RelationPropertyConfiguration) |
| 125 | + } |
| 126 | + |
| 127 | + async def create_page( |
| 128 | + self, |
| 129 | + properties: Dict[str, Any] = {}, |
| 130 | + cover_url: Optional[str] = None, |
| 131 | + ) -> NotionPage: |
| 132 | + """Creates a new page in the Data Source and updates the new page with |
| 133 | + the properties. |
| 134 | +
|
| 135 | + Args: |
| 136 | + properties: Dictionary of property names and values. Value types |
| 137 | + will depend on the property type. Can be the raw value |
| 138 | + (e.g. string, float) or an object (e.g. SelectValue, |
| 139 | + NumberPropertyItem) |
| 140 | + cover_url: URL of an image for the page cover. |
| 141 | + """ |
| 142 | + |
| 143 | + validated_properties = {} |
| 144 | + for prop_name, prop_value in properties.items(): |
| 145 | + prop = self.properties.get(prop_name, None) |
| 146 | + if prop is None: |
| 147 | + raise ValueError(f"Unknown property: {prop_name}") |
| 148 | + value = generate_value(prop.config_type, prop_value) |
| 149 | + validated_properties[prop_name] = value |
| 150 | + |
| 151 | + request = NotionDataSource.CreatePageRequest( |
| 152 | + parent=ParentObject( |
| 153 | + type="data_source_id", data_source_id=self.data_source_id |
| 154 | + ), |
| 155 | + properties=validated_properties, |
| 156 | + cover=( |
| 157 | + FileObject.from_url(cover_url) |
| 158 | + if cover_url is not None |
| 159 | + else None |
| 160 | + ), |
| 161 | + ) |
| 162 | + |
| 163 | + data = request.json(by_alias=True, exclude_unset=True) |
| 164 | + |
| 165 | + new_page = await self._api._post("pages", data=data) |
| 166 | + |
| 167 | + return NotionPage( |
| 168 | + api=self._api, |
| 169 | + page_id=new_page.page_id, |
| 170 | + obj=new_page, |
| 171 | + data_source=self, |
| 172 | + ) |
0 commit comments