notion package¶
Subpackages¶
Submodules¶
notion.client module¶
-
exception
notion.client.
InvalidCollectionViewUrl
(message: str, **extra)[source]¶ Bases:
notion.client.NotionApiError
-
class
notion.client.
NotionClient
(token_v2: str = '', enable_monitoring: bool = False, start_monitoring: bool = False, enable_caching: bool = False, cache_key: str = '')[source]¶ Bases:
object
This is the entry point to using the API.
Create an instance of this class, passing it the value of the “token_v2” cookie from a logged-in browser session on Notion.so.
-
__init__
(token_v2: str = '', enable_monitoring: bool = False, start_monitoring: bool = False, enable_caching: bool = False, cache_key: str = '')[source]¶ Create NotionClient object and fill its fields.
Parameters: - token_v2 (str, optional) – The cookie from logged-in browser session on notion.so. If not provided then all operations will be ran as if user was not logged in. Defaults to empty string.
- enable_monitoring (bool, optional) – Whether or not to monitor the records managed by NotionClient. Defaults to False.
- start_monitoring (bool, optional) – Whether or not to start monitoring immediately upon logging in. This option takes effect only when monitor is True. Defaults to False.
- enable_caching (bool, optional) – Whether or not to enable caching of fetched data to file. Defaults to False.
- cache_key (str, optional) – The key string used for storing all cached data in file. This option takes effect only when enable_caching is True. Defaults to SHA256 of token_v2.
-
as_atomic_transaction
() → notion.client.Transaction[source]¶ Returns a context manager that buffers up all calls to submit_transaction and sends them as one big transaction when the context manager exits.
Returns: Initialised transaction object. Return type: Transaction
-
create_record
(table: str, parent: notion.block.basic.Block, **kwargs) → str[source]¶ Create new record.
Parameters: - table (str) – Table value.
- parent (Block) – Parent for the newly created record.
Returns: ID of newly created record.
Return type: str
-
download_block
(block_id: str, recursive: bool = False, export_type: str = 'markdown', time_zone: str = 'America/Chicago', locale: str = 'en')[source]¶ Download block.
TODO: Add support for downloading a list of blocks.
Parameters: - block_id (str) – ID of the block.
- recursive (bool, optional) – Whether or not to include sub pages. Defaults to False.
- export_type (str) – Type of the output file. The options are “markdown”, “pdf”, “html”. Defaults to “markdown”.
- time_zone (str, optional) – I don’t know what values go here. I’m in the Chicago timezone (central) and this is what I saw in the request. Defaults to “America/Chicago”. TODO: test? hard code?
- locale (str, optional) – Locale for the export. Defaults to “en”.
-
get
(endpoint: str) → requests.models.Response[source]¶ Send HTTP GET request to given endpoint or URL.
Parameters: endpoint (str) – Notion’s endpoint to aim at. Returns: Whatever API sent back. Return type: Response
-
get_block
(url_or_id: str, force_refresh: bool = False) → Optional[notion.block.basic.Block][source]¶ Retrieve an instance of a subclass of Block that maps to the block/page identified by the URL or ID passed in.
Parameters: - url_or_id (str) – Path or ID to block.
- force_refresh (bool, optional) – Whether or not to force a refresh of data. Defaults to False.
Returns: Found block or None.
Return type: Block or None
-
get_collection
(collection_id: str, force_refresh: bool = False) → Optional[notion.block.collection.basic.CollectionBlock][source]¶ Retrieve an instance of Collection that maps to the collection identified by the ID passed in.
Parameters: - collection_id (str) – ID of searched collection.
- force_refresh (bool, optional) – Whether or not to force a refresh of data. Defaults to False.
Returns: Found collection or None.
Return type:
-
get_collection_view
(url_or_id: str, collection: notion.block.collection.basic.CollectionBlock = None, force_refresh: bool = False) → Optional[notion.block.collection.view.CollectionView][source]¶ Retrieve an instance of a subclass of CollectionView that maps to the appropriate type.
The url_or_id argument can either be the URL for a database page, or the ID of a collection_view (in which case you must pass the collection)
Parameters: - url_or_id (str) – ID of searched collection view.
- collection (Collection) – object representing ID of searched collection view.
- force_refresh (bool, optional) – Whether or not to force a refresh of data. Defaults to False.
Raises: InvalidCollectionViewUrl
– When passed in URL is invalid.Returns: Found collectionView or None.
Return type:
-
get_record_data
(table: str, url_or_id: str, force_refresh: bool = False) → dict[source]¶ Get record data.
Parameters: - table (str) – A “block type” in notion.so terminology.
- url_or_id (str) – Path or ID to block.
- force_refresh (bool, optional) – Whether or not to force a refresh of data. Defaults to False.
Returns: Record data.
Return type: dict
-
get_space
(space_id: str, force_refresh: bool = False) → Optional[notion.space.NotionSpace][source]¶ Retrieve an instance of Space that maps to the space identified by the ID passed in.
Parameters: - space_id (str) – ID of searched user.
- force_refresh (bool, optional) – Whether or not to force a refresh of data. Defaults to False.
Returns: Found space or None.
Return type:
-
get_top_level_pages
() → list[source]¶ Get list of top level pages defined in Notion Workspace.
Returns: Top level pages. Return type: list of Block
-
get_user
(user_id: str, force_refresh: bool = False) → Optional[notion.user.NotionUser][source]¶ Retrieve an instance of User that maps to the notion_user identified by the ID passed in.
Parameters: - user_id (str) – ID of searched user.
- force_refresh (bool, optional) – Whether or not to force a refresh of data. Defaults to False.
Returns: Found user or None.
Return type:
-
post
(endpoint: str, data: dict = None, **kwargs) → requests.models.Response[source]¶ Send HTTP POST request to given endpoint or URL.
All API requests on Notion.so are done as POSTs, except the websocket communications.
Parameters: - endpoint (str) – Notion’s endpoint to aim at.
- data (dict) – Data to send. Defaults to empty dict.
- kwargs (dict) – Additional params to post(). Defaults to empty dict.
Raises: NotionValidationError
– When POST fails with HTTP 400.NotionUnauthorizedError
– When POST fails with HTTP 401.NotionApiError
– When POST fails in a different way.
Returns: Whatever API sent back.
Return type: Response
-
put
(endpoint: str, data: dict = None, **kwargs) → requests.models.Response[source]¶ Send HTTP PUT request to given endpoint or URL.
Parameters: - endpoint (str) – Notion’s endpoint to aim at.
- data (dict) – Data to send. Defaults to None.
- kwargs (dict) – Additional params for put(). Defaults to empty dict.
Returns: Whatever API sent back.
Return type: Response
-
refresh_collection_rows
(collection_id: str)[source]¶ Refresh collection rows.
Parameters: collection_id (str) – ID of the collection.
-
refresh_records
(**kwargs)[source]¶ The keyword arguments map table names into lists of (or singular) record IDs to load for that table.
Use True instead of a list to refresh all known records for that table.
-
search_blocks
(search: str, limit: int = 20) → List[notion.block.basic.Block][source]¶ Search for blocks.
Parameters: - search (str) – Text to search by.
- limit (int, optional) – Max number of blocks to return. Defaults to 20.
Returns: List of blocks.
Return type: list
-
search_pages_with_parent
(parent_id: str, search: str = '', limit: int = 10000) → list[source]¶ Search for pages with parent.
Parameters: - parent_id (str) – ID of parent block.
- search (str, optional) – Text to search by. Defaults to empty string.
- limit (int, optional) – Max number of pages to return. Defaults to 10_000.
Returns: List of results.
Return type: list
-
start_monitoring
()[source]¶ Start monitoring the tracked blocks.
This function will create new Thread.
-
submit_transaction
(operations: Union[list, dict], update_last_edited: bool = True)[source]¶ Submit list of operations in atomic transaction block.
Parameters: - operations (list or dict) – List of operations to submit.
- update_last_edited (bool, optional) – Whether or not to automatically update last edited records. Defaults to True.
-
Bases:
notion.client.NotionApiError
-
exception
notion.client.
NotionValidationError
(message: str, **extra)[source]¶ Bases:
notion.client.NotionApiError
-
class
notion.client.
Transaction
(client)[source]¶ Bases:
object
Transaction object.
-
__init__
(client)[source]¶ Create Transaction object.
Parameters: client (NotionClient) – Client object to use for transaction.
-
notion.converter module¶
-
class
notion.converter.
BaseConverter
[source]¶ Bases:
object
Base Converter.
-
classmethod
convert
(name: str, value: Any, prop: dict, block) -> (<class 'str'>, typing.Any)[source]¶ Convert value from attribute name.
-
name
¶ Property name.
Type: str
-
value
¶ Value to convert.
Type: Any
-
prop
¶ More information about the block property.
Type: dict
Returns: Tuple containing property path and converted value. Return type: (str, Any) -
-
classmethod
notion.logger module¶
notion.maps module¶
-
class
notion.maps.
Mapper
(path: str, python_to_api: Callable, api_to_python: Callable, *args, **kwargs)[source]¶ Bases:
property
Mapper for converting to/from notion and Python.
-
__init__
(path: str, python_to_api: Callable, api_to_python: Callable, *args, **kwargs)[source]¶ Create mapper object and fill its fields.
Parameters: - path (str) – Path can either be a top-level field-name or a dot-delimited string representing the key names to traverse.
- python_to_api (Callable) – Function that converts values as given in the Python layer into the internal API representation.
- api_to_python (Callable) – Function that converts what is received from the API into an internal representation to be returned to the Python layer.
-
-
notion.maps.
boolean_property_map
(name: str) → notion.maps.Mapper[source]¶ Parameters: name (str) – Name of the property. Returns: Property map. Return type: Mapper See also
-
notion.maps.
field_map
(path: str, python_to_api: Callable = <function <lambda>>, api_to_python: Callable = <function <lambda>>) → notion.maps.Mapper[source]¶ Return a property that maps a Block attribute onto a field in the API data structures.
Parameters: - path (str) – Path can either be a top-level field-name or a dot-delimited string representing the key names to traverse.
- python_to_api (Callable, optional) – Function that converts values as given in the Python layer into the internal API representation. Defaults to proxy lambda x: x.
- api_to_python (Callable, optional) – Function that converts what is received from the API into an internal representation to be returned to the Python layer. Defaults to proxy lambda x: x.
Returns: Property map.
Return type: See also
-
notion.maps.
markdown_field_map
(name: str) → notion.maps.Mapper[source]¶ Parameters: name (str) – Name of the property. Returns: Field map. Return type: Mapper See also
-
notion.maps.
nested_field_map
(name: str) → notion.maps.Mapper[source]¶ Parameters: name (str) – Name of the property. Returns: Field map. Return type: Mapper See also
-
notion.maps.
plaintext_property_map
(name: str) → notion.maps.Mapper[source]¶ Parameters: name (str) – Name of the property. Returns: Property map. Return type: Mapper See also
-
notion.maps.
prefixed_field_map
(name: str) → notion.maps.Mapper[source]¶ Parameters: name (str) – Name of the property. Returns: Field map. Return type: Mapper See also
-
notion.maps.
prefixed_property_map
(name: str) → notion.maps.Mapper[source]¶ Parameters: name (str) – Name of the property. Returns: Property map. Return type: Mapper See also
-
notion.maps.
property_map
(name: str, python_to_api: Callable = <function <lambda>>, api_to_python: Callable = <function <lambda>>, markdown: bool = True) → notion.maps.Mapper[source]¶ Similar to field_map, except it works specifically with the data under the “properties” field in the API block table, and just takes a single name to specify which subkey to reference.
Also, these properties all seem to use a special “embedded list” format that breaks the text up into a sequence of chunks and associated format metadata.
Parameters: - name (str) – Name of the property.
- python_to_api (Callable, optional) – Function that converts values as given in the Python layer into the internal API representation. Defaults to proxy lambda x: x.
- api_to_python (Callable, optional) – Function that converts what is received from the API into an internal representation to be returned to the Python layer. Defaults to proxy lambda x: x.
- markdown (bool, optional) – Whether or not to convert the representation into commonmark-compatible markdown text upon reading from API and again when saving. Defaults to True.
Returns: Property map.
Return type: See also
notion.markdown module¶
-
notion.markdown.
markdown_to_notion
(markdown: str) → list[source]¶ Convert Markdown formatted string to Notion.
Parameters: markdown (str) – Text to convert. Returns: Blocks converted from input. Return type: list of Block
-
notion.markdown.
notion_to_markdown
(notion: list) → str[source]¶ Convert list of notion blocks to markdown text.
Parameters: notion (list) – List of Notion Blocks TODO: is it true? Raises: Exception
– When it’s unable to extract text.Returns: Converted Markdown text. Return type: str
-
notion.markdown.
notion_to_plaintext
(notion: list, client=None) → str[source]¶ Convert list of notion blocks to plain text.
Parameters: - notion (list) – Text in a Notion specific API format i.e. [[“some text”]]
- client (NotionClient, optional) – Used for getting blocks, if passed. Defaults to None.
Returns: Converted text.
Return type: str
notion.monitor module¶
-
class
notion.monitor.
Monitor
(client, root_url: str = 'https://msgstore.www.notion.so/primus/')[source]¶ Bases:
object
Monitor class for automatic data polling of records.
-
__init__
(client, root_url: str = 'https://msgstore.www.notion.so/primus/')[source]¶ Create Monitor object.
Parameters: - client (NotionClient) – Client to use.
- root_url (str, optional) – Root URL for polling message stats. Defaults to valid notion message store URL.
-
poll
(retries: int = 10)[source]¶ Poll for changes.
Parameters: retries (int, optional) – Number of times to retry request if it fails. Should be bigger than 5. Defaults to 10. Raises: HTTPError
– When GET request fails for retries times.
-
poll_forever
()[source]¶ Call poll() in never-ending loop with small time intervals in-between.
This function is blocking, it never returns!
-
post_data
(data: bytes)[source]¶ Send monitoring requests to Notion.
Parameters: data (bytes) – Form encoded request data.
-
subscribe
(records: Set[notion.record.Record])[source]¶ Subscribe to changes of passed records.
Parameters: records (set of Record) – Set of Record objects to subscribe to.
-
thread
= None¶
-
notion.operations module¶
-
notion.operations.
build_operations
(record_id: str, path: str, args: dict, command: str, table: str = 'block') → dict[source]¶ Build sequence of operations for submitTransaction endpoint.
Parameters: - record_id (str) – ID of the object.
- path (str) – Key for the object.
- args (dict) – Arguments.
- command (str) – Command to execute.
- table (str, optional) – Table argument for endpoint. Defaults to “block”.
Returns: Valid dict for the endpoint.
Return type: dict
-
notion.operations.
operation_update_last_edited
(user_id, record_id) → dict[source]¶ Convenience function for constructing “last edited” operation.
When transactions are submitted from the web UIit also includes an operation to update the “last edited” fields, so we want to send those too, for consistency.
Parameters: - user_id (str) – User ID
- record_id (str) – ID of the object.
Returns: Constructed dict with last edited operation included.
Return type: dict
notion.record module¶
-
class
notion.record.
Record
(client, block_id: str, *args, **kwargs)[source]¶ Bases:
object
Basic collection of information about a notion-like block.
-
add_callback
(cb: Callable, cb_id: str = '', **extra_kwargs) → notion.store.Callback[source]¶ Add callback function to listeners.
Parameters: - cb (Callable) – Function that should be called.
- cb_id (str, optional) – Identification key for the callback. Defaults to random UUID string.
- extra_kwargs (dict, optional) – Additional information that should be passed to callback when executed. Defaults to empty dict.
Returns: Callback object.
Return type:
-
get
(path: str = '', default: Any = None, force_refresh: bool = False) → Union[dict, str][source]¶ Retrieve cached data for this record.
Parameters: - path (str, optional) – Specifies the field to retrieve the value for. If no path is supplied, return the entire cached data structure for this record. Defaults to empty string.
- default (Any, optional) – Default value to return if no value was found under provided path. Defaults to None.
- force_refresh (bool, optional) – If set to True, force refresh the data cache from the server before reading the values. Defaults to False.
Returns: Cached data.
Return type: Union[dict, str]
-
id
¶ Get the Record ID.
Returns: Record ID Return type: str
-
refresh
()[source]¶ Update the cached data for this record from the server.
Data for other records may be updated as a side effect.
-
remove_callbacks
(cb_or_cb_id_prefix: Union[notion.store.Callback, str] = None)[source]¶ Remove one or more callbacks based on their ID prefix.
Parameters: cb_or_cb_id_prefix (Callback or str, optional) – Callback to remove or prefix of callback IDs to remove.
-
role
¶ Get the Record role.
Returns: Record role Return type: str
-
set
(path: str, value: Any)[source]¶ Set a specific value under the specific path on the record’s data structure on the server.
Parameters: - path (str) – Specifies the field to which set the value.
- value (Any) – Value to set under provided path.
-
space_info
¶
-
url
¶ Get the URL.
Returns: URL ro Record. Return type: str
-
notion.renderer module¶
-
class
notion.renderer.
BaseHTMLRenderer
(start_block: notion.block.basic.Block, exclude_ids: list = None, render_sub_pages: bool = True, render_with_styles: bool = False, render_linked_pages: bool = False, render_table_pages_after_table: bool = False, render_sub_pages_links: bool = True)[source]¶ Bases:
object
BaseRenderer for HTML output.
Uses [Dominate](https://github.com/Knio/dominate) internally for generating HTML output. Each token rendering method should create a dominate tag and it automatically gets added to the parent context (because of the with statement). If you return a given tag, it will be used as the parent container for all rendered children
-
__init__
(start_block: notion.block.basic.Block, exclude_ids: list = None, render_sub_pages: bool = True, render_with_styles: bool = False, render_linked_pages: bool = False, render_table_pages_after_table: bool = False, render_sub_pages_links: bool = True)[source]¶ -
-
exclude_ids
¶ Optional list of Block IDs to skip when rendering. Defaults to None.
Type: list of str, optional
-
render_sub_pages
¶ Whether to render sub pages. Defaults to True.
Type: bool, optional
-
render_sub_pages_links
¶ Whether to render sub pages as a link at the bottom, if render_sub_pages = False Defaults to False.
Type: bool, optional
-
render_with_styles
¶ Whether to include CSS styles inside rendered HTML. Defaults to False.
Type: bool, optional
-
render_linked_pages
¶ Whether to render linked pages as well. Defaults to False.
Type: bool, optional
-
# TODO
Type: what?
-
render_table_pages_after_table
¶ Whether to render linked pages after table. Defaults to False.
Type: bool, optional
-
-
render
(indent: str = ' ', pretty: bool = True, xhtml: bool = False) → str[source]¶ Renders the HTML, kwargs takes kwargs for render() function https://github.com/Knio/dominate#rendering
-
indent
¶ String used for indenting the rendered text. Defaults to str consisting of two spaces.
Type: str, optional
-
pretty
¶ Whether or not to render the HTML in a human-readable way. Defaults to True.
Type: bool, optional
-
xhtml
¶ Whether or not to use XHTML instead of HTML. Example: <br /> instead of <br> Defaults to False.
Type: bool, False
Returns: Rendered blocks. Return type: str -
-
notion.settings module¶
notion.space module¶
-
class
notion.space.
NotionSpace
(client, block_id: str, *args, **kwargs)[source]¶ Bases:
notion.record.Record
Class representing notion’s Space - user workplace.
-
add_page
(title, type: str = 'page', shared: bool = False) → Union[notion.block.basic.PageBlock, notion.block.collection.media.CollectionViewPageBlock][source]¶ Create new page.
Parameters: - title (str) – Title for the newly created page.
- type (str, optional) – Type of the page. Must be one of “page” or “collection_view_page”. Defaults to “page”.
- shared (bool, optional) – Whether or not the page should be shared (public). TODO: is it true? Defaults to False.
-
domain
¶
-
icon
¶
-
name
¶
-
pages
¶
-
users
¶
-
notion.store module¶
-
class
notion.store.
Callback
(callback: Callable, record, callback_id: str = None, **kwargs)[source]¶ Bases:
object
-
class
notion.store.
RecordStore
(client, cache_key=None)[source]¶ Bases:
object
Central Record Store.
-
call_get_record_values
(**kwargs)[source]¶ Call the server’s getRecordValues endpoint to update the local record store. The keyword arguments map table names into lists of (or singular) record IDs to load for that table. Use True to refresh all known records for that table.
-
call_query_collection
(collection_id: str, collection_view_id: str, search: str = '', type: str = 'table', aggregate: list = None, aggregations: list = None, filter: dict = None, filter_operator: str = 'and', sort: list = [], calendar_by: str = '', group_by: str = '')[source]¶
-
notion.user module¶
notion.utils module¶
-
notion.utils.
add_signed_prefix_as_needed
(url: str, client=None) → str[source]¶ Utility function for adding signed prefix to URL.
Parameters: - url (str) – URL to operate on.
- client (NotionClient, optional) – It’s used for making wrapped requests via initialized requests.Session object. Defaults to None.
Returns: Prefixed URL.
Return type: str
-
notion.utils.
extract_id
(source) → Optional[str][source]¶ Extract the record ID from a block or Notion.so URL.
If it’s a bare page URL, it will be the ID of the page. If there’s a hash with a block ID in it (from clicking “Copy Link”) on a block in a page), it will instead be the ID of that block. If it’s already in ID format, it will be passed right through. If it’s a Block, it will be the ID of a block.
Parameters: source (Block or str) – Block or Link to block or its ID. Returns: ID of the block or None. Return type: str
-
notion.utils.
from_list
(value) → Any[source]¶ Unwrap value from nested list.
Parameters: value (List) – Nested list with target value. Returns: Value from nested list. Return type: Any
-
notion.utils.
get_by_path
(path: str, obj: Any, default: Any = None) → Any[source]¶ Get value from object’s key by dotted path (i.e. “path.to.0.some.key”).
Parameters: - path (str) – Path in string form.
- obj (Any) – Object to traverse.
- default (Any, optional) – Default value if key was invalid. Defaults to None.
Returns: Value stored under specified key or default value.
Return type: Any
-
notion.utils.
get_embed_link
(source_url: str, client) → str[source]¶ Get embed link.
Parameters: - source_url (str) – Source URL from which the embedded link will be extracted.
- client (NotionClient) – Client used for sending the actual request.
Returns: Extracted link.
Return type: str
-
notion.utils.
human_size
(path: str, divider: int = 1024) → str[source]¶ Get human readable file size.
Parameters: - path (str) – Path to the file.
- divider (int, optional) – Divider used for calculations, use 1000 or 1024. Defaults to 1024.
Returns: Converted size.
Return type: str
-
notion.utils.
now
() → int[source]¶ Get UNIX-style time since epoch in seconds.
Returns: Time since epoch in seconds. Return type: int
-
notion.utils.
remove_signed_prefix_as_needed
(url: str) → str[source]¶ Utility function for removing signed prefix from URL.
Parameters: url (str) – URL to operate on. Returns: Non-prefixed URL. Return type: str
-
notion.utils.
slugify
(text: str) → str[source]¶ Convert text to computer-friendly simplified form.
Parameters: text (str) – String to operate on. Returns: Converted string. Return type: str