Skip to content

block

notion.block

RESEARCH_API_PATH module-attribute

RESEARCH_API_PATH = 'http://data.saige.in:8000/workspaces/notion/research_api_token.txt'

BLOCKS module-attribute

BLOCKS = {}

RICH_TEXT_LIMIT module-attribute

RICH_TEXT_LIMIT = 2000

Block

Block(value, **kwargs)

Notion Block objects. It converts values into block object structures specified by the notion api. Additionally, it can check whether given value is valid for the property.

Source code in ResearchToolkit/notion/block.py
def __init__(self, value, **kwargs):
    self.value = value
    self.out = {self.name: self.value}

value instance-attribute

value = value

out instance-attribute

out = {name: value}

__init_subclass__

__init_subclass__(**kwargs)
Source code in ResearchToolkit/notion/block.py
def __init_subclass__(cls, **kwargs):
    super().__init_subclass__(**kwargs)
    cls.name = pascal_to_snake(cls.__name__)
    register(cls)

__call__

__call__()
Source code in ResearchToolkit/notion/block.py
def __call__(self):
    return self.out

Heading1

Heading1(value, color: Optional[str] = None)

Bases: Block

Source code in ResearchToolkit/notion/block.py
def __init__(self, value, color: Optional[str] = None):
    super(Heading1, self).__init__(value)
    self.out = {self.name: {"rich_text": [{"text": {"content": value}}]}}
    if color in [
        "default",
        "gray",
        "brown",
        "orange",
        "yellow",
        "green",
        "blue",
        "purple",
        "pink",
        "red",
        "gray_background",
        "brown_background",
        "orange_background",
        "yellow_background",
        "green_background",
        "blue_background",
        "purple_background",
        "pink_background",
        "red_background",
    ]:
        self.out[self.name].update({"color": color})

out instance-attribute

out = {name: {'rich_text': [{'text': {'content': value}}]}}

__bool__

__bool__()
Source code in ResearchToolkit/notion/block.py
def __bool__(self):
    return isinstance(self.value, str)

Heading2

Heading2(value, color: Optional[str] = None)

Bases: Heading1

Source code in ResearchToolkit/notion/block.py
def __init__(self, value, color: Optional[str] = None):
    super(Heading1, self).__init__(value)
    self.out = {self.name: {"rich_text": [{"text": {"content": value}}]}}
    if color in [
        "default",
        "gray",
        "brown",
        "orange",
        "yellow",
        "green",
        "blue",
        "purple",
        "pink",
        "red",
        "gray_background",
        "brown_background",
        "orange_background",
        "yellow_background",
        "green_background",
        "blue_background",
        "purple_background",
        "pink_background",
        "red_background",
    ]:
        self.out[self.name].update({"color": color})

Heading3

Heading3(value, color: Optional[str] = None)

Bases: Heading1

Source code in ResearchToolkit/notion/block.py
def __init__(self, value, color: Optional[str] = None):
    super(Heading1, self).__init__(value)
    self.out = {self.name: {"rich_text": [{"text": {"content": value}}]}}
    if color in [
        "default",
        "gray",
        "brown",
        "orange",
        "yellow",
        "green",
        "blue",
        "purple",
        "pink",
        "red",
        "gray_background",
        "brown_background",
        "orange_background",
        "yellow_background",
        "green_background",
        "blue_background",
        "purple_background",
        "pink_background",
        "red_background",
    ]:
        self.out[self.name].update({"color": color})

Paragraph

Paragraph(value, color: Optional[str] = None, children: Optional[Union[dict, List[dict]]] = None)

Bases: Heading1

summary

Parameters:

  • value (_type_) –

    description

  • color (Optional[str], default: None ) –

    description. Defaults to None.

  • children (Optional[Union[dict, List[dict]]], default: None ) –

    children should be output or list of Block object output. e.g) Paragraph("hello world")() or [Heading1("Tutorial")(), Paragraph("hello world")()]

Source code in ResearchToolkit/notion/block.py
def __init__(
    self, value, color: Optional[str] = None, children: Optional[Union[dict, List[dict]]] = None
):
    """_summary_

    Args:
        value (_type_): _description_
        color (Optional[str], optional): _description_. Defaults to None.
        children (Optional[Union[dict, List[dict]]], optional): children should be output or list of `Block` object output.
                                                                e.g) Paragraph("hello world")()
                                                                    or [Heading1("Tutorial")(), Paragraph("hello world")()]
    """
    super(Paragraph, self).__init__(value, color)
    if children:
        if isinstance(children, dict):
            children = [children]
        self.out[self.name].update({"children": children})

Callout

Callout(value, color: Optional[str] = None, children: Optional[Union[dict, List[dict]]] = None)

Bases: Paragraph

summary

Parameters:

  • value (_type_) –

    description

  • color (Optional[str], default: None ) –

    description. Defaults to None.

  • children (Optional[Union[dict, List[dict]]], default: None ) –

    children should be output or list of Block object output. e.g) Paragraph("hello world")() or [Heading1("Tutorial")(), Paragraph("hello world")()]

Source code in ResearchToolkit/notion/block.py
def __init__(
    self, value, color: Optional[str] = None, children: Optional[Union[dict, List[dict]]] = None
):
    """_summary_

    Args:
        value (_type_): _description_
        color (Optional[str], optional): _description_. Defaults to None.
        children (Optional[Union[dict, List[dict]]], optional): children should be output or list of `Block` object output.
                                                                e.g) Paragraph("hello world")()
                                                                    or [Heading1("Tutorial")(), Paragraph("hello world")()]
    """
    super(Paragraph, self).__init__(value, color)
    if children:
        if isinstance(children, dict):
            children = [children]
        self.out[self.name].update({"children": children})

Quote

Quote(value, color: Optional[str] = None, children: Optional[Union[dict, List[dict]]] = None)

Bases: Paragraph

summary

Parameters:

  • value (_type_) –

    description

  • color (Optional[str], default: None ) –

    description. Defaults to None.

  • children (Optional[Union[dict, List[dict]]], default: None ) –

    children should be output or list of Block object output. e.g) Paragraph("hello world")() or [Heading1("Tutorial")(), Paragraph("hello world")()]

Source code in ResearchToolkit/notion/block.py
def __init__(
    self, value, color: Optional[str] = None, children: Optional[Union[dict, List[dict]]] = None
):
    """_summary_

    Args:
        value (_type_): _description_
        color (Optional[str], optional): _description_. Defaults to None.
        children (Optional[Union[dict, List[dict]]], optional): children should be output or list of `Block` object output.
                                                                e.g) Paragraph("hello world")()
                                                                    or [Heading1("Tutorial")(), Paragraph("hello world")()]
    """
    super(Paragraph, self).__init__(value, color)
    if children:
        if isinstance(children, dict):
            children = [children]
        self.out[self.name].update({"children": children})

BulletedListItem

BulletedListItem(value, color: Optional[str] = None, children: Optional[Union[dict, List[dict]]] = None)

Bases: Paragraph

summary

Parameters:

  • value (_type_) –

    description

  • color (Optional[str], default: None ) –

    description. Defaults to None.

  • children (Optional[Union[dict, List[dict]]], default: None ) –

    children should be output or list of Block object output. e.g) Paragraph("hello world")() or [Heading1("Tutorial")(), Paragraph("hello world")()]

Source code in ResearchToolkit/notion/block.py
def __init__(
    self, value, color: Optional[str] = None, children: Optional[Union[dict, List[dict]]] = None
):
    """_summary_

    Args:
        value (_type_): _description_
        color (Optional[str], optional): _description_. Defaults to None.
        children (Optional[Union[dict, List[dict]]], optional): children should be output or list of `Block` object output.
                                                                e.g) Paragraph("hello world")()
                                                                    or [Heading1("Tutorial")(), Paragraph("hello world")()]
    """
    super(Paragraph, self).__init__(value, color)
    if children:
        if isinstance(children, dict):
            children = [children]
        self.out[self.name].update({"children": children})

NumberedListItem

NumberedListItem(value, color: Optional[str] = None, children: Optional[Union[dict, List[dict]]] = None)

Bases: Paragraph

summary

Parameters:

  • value (_type_) –

    description

  • color (Optional[str], default: None ) –

    description. Defaults to None.

  • children (Optional[Union[dict, List[dict]]], default: None ) –

    children should be output or list of Block object output. e.g) Paragraph("hello world")() or [Heading1("Tutorial")(), Paragraph("hello world")()]

Source code in ResearchToolkit/notion/block.py
def __init__(
    self, value, color: Optional[str] = None, children: Optional[Union[dict, List[dict]]] = None
):
    """_summary_

    Args:
        value (_type_): _description_
        color (Optional[str], optional): _description_. Defaults to None.
        children (Optional[Union[dict, List[dict]]], optional): children should be output or list of `Block` object output.
                                                                e.g) Paragraph("hello world")()
                                                                    or [Heading1("Tutorial")(), Paragraph("hello world")()]
    """
    super(Paragraph, self).__init__(value, color)
    if children:
        if isinstance(children, dict):
            children = [children]
        self.out[self.name].update({"children": children})

ToDo

ToDo(value, checked: Optional[bool] = None, color: Optional[str] = None, children: Optional[Union[dict, List[dict]]] = None)

Bases: Paragraph

Source code in ResearchToolkit/notion/block.py
def __init__(
    self,
    value,
    checked: Optional[bool] = None,
    color: Optional[str] = None,
    children: Optional[Union[dict, List[dict]]] = None,
):
    super(ToDo, self).__init__(value, color, children)
    if checked:
        self.out[self.name].update({"checked": checked})

Toggle

Toggle(value, color: Optional[str] = None, children: Optional[Union[dict, List[dict]]] = None)

Bases: Paragraph

summary

Parameters:

  • value (_type_) –

    description

  • color (Optional[str], default: None ) –

    description. Defaults to None.

  • children (Optional[Union[dict, List[dict]]], default: None ) –

    children should be output or list of Block object output. e.g) Paragraph("hello world")() or [Heading1("Tutorial")(), Paragraph("hello world")()]

Source code in ResearchToolkit/notion/block.py
def __init__(
    self, value, color: Optional[str] = None, children: Optional[Union[dict, List[dict]]] = None
):
    """_summary_

    Args:
        value (_type_): _description_
        color (Optional[str], optional): _description_. Defaults to None.
        children (Optional[Union[dict, List[dict]]], optional): children should be output or list of `Block` object output.
                                                                e.g) Paragraph("hello world")()
                                                                    or [Heading1("Tutorial")(), Paragraph("hello world")()]
    """
    super(Paragraph, self).__init__(value, color)
    if children:
        if isinstance(children, dict):
            children = [children]
        self.out[self.name].update({"children": children})

Code

Code(value, caption: Optional[str] = None, language: Optional[str] = None)

Bases: Block

Source code in ResearchToolkit/notion/block.py
def __init__(self, value, caption: Optional[str] = None, language: Optional[str] = None):
    super(Code, self).__init__(value)
    self.out = {self.name: {"rich_text": [{"text": {"content": value}}]}}
    if caption:
        self.out[self.name].update({"caption": [{"text": {"content": caption}}]})
    if language.lower() in [
        "abap",
        "arduino",
        "bash",
        "basic",
        "c",
        "clojure",
        "coffeescript",
        "c++",
        "c#",
        "css",
        "dart",
        "diff",
        "docker",
        "elixir",
        "elm",
        "erlang",
        "flow",
        "fortran",
        "f#",
        "gherkin",
        "glsl",
        "go",
        "graphql",
        "groovy",
        "haskell",
        "html",
        "java",
        "javascript",
        "json",
        "julia",
        "kotlin",
        "latex",
        "less",
        "lisp",
        "livescript",
        "lua",
        "makefile",
        "markdown",
        "markup",
        "matlab",
        "mermaid",
        "nix",
        "objective-c",
        "ocaml",
        "pascal",
        "perl",
        "php",
        "plain text",
        "powershell",
        "prolog",
        "protobuf",
        "python",
        "r",
        "reason",
        "ruby",
        "rust",
        "sass",
        "scala",
        "scheme",
        "scss",
        "shell",
        "sql",
        "swift",
        "typescript",
        "vb.net",
        "verilog",
        "vhdl",
        "visual basic",
        "webassembly",
        "xml",
        "yaml",
        "java/c/c++/c#",
    ]:
        self.out[self.name].update({"language": language})

out instance-attribute

out = {name: {'rich_text': [{'text': {'content': value}}]}}

__bool__

__bool__()
Source code in ResearchToolkit/notion/block.py
def __bool__(self):
    return isinstance(self.value, str)

get_token

get_token(token_path: str = RESEARCH_API_PATH)
Source code in ResearchToolkit/notion/common.py
def get_token(token_path: str = RESEARCH_API_PATH):
    if "http" in token_path:
        token = urlopen(token_path).read().decode("utf-8")
    else:
        with open(token_path, "r") as file:
            token = file.read()

    return token

pascal_to_snake

pascal_to_snake(name)
Source code in ResearchToolkit/notion/common.py
def pascal_to_snake(name):
    return "_".join(re.sub(r"([A-Z])", r" \1", name).split()).lower()

register

register(cls)
Source code in ResearchToolkit/notion/block.py
def register(cls):
    BLOCKS[cls.name] = cls
    return cls

make_rich_text_blocks

make_rich_text_blocks(name: str, text: str, **kwargs) -> List[Dict]

text를 block 길이 제한 만큼 잘라서 block들의 리스트로 변환합니다.

Parameters:

  • name (str) –

    block 종류

  • text (str) –

    컨텐츠 텍스트

Returns:

  • List[Dict]

    List[Dict]: append_block_children에 입력할 수 있는 block들

Source code in ResearchToolkit/notion/block.py
def make_rich_text_blocks(name: str, text: str, **kwargs) -> List[Dict]:
    """text를 block 길이 제한 만큼 잘라서 block들의 리스트로 변환합니다.

    Args:
        name (str): block 종류
        text (str): 컨텐츠 텍스트

    Returns:
        List[Dict]: append_block_children에 입력할 수 있는 block들
    """
    text_chuncks = [text[i : i + RICH_TEXT_LIMIT] for i in range(0, len(text), RICH_TEXT_LIMIT)]
    blocks = [BLOCKS[name](chunck, **kwargs)() for chunck in text_chuncks]
    return blocks

retrieve_block_children

retrieve_block_children(page_id: str, token_path: str = RESEARCH_API_PATH, token: Optional[str] = None)

get all blocks on notion page. Args: page_id (str): notion page_id to search token_path (str, optional): description. Defaults to RESEARCH_API_PATH. token (Optional[str], optional): description. Defaults to None.

Returns:

  • _type_

    request response code (200 if succeeded) and response text, block_children

Source code in ResearchToolkit/notion/block.py
def retrieve_block_children(
    page_id: str,
    token_path: str = RESEARCH_API_PATH,
    token: Optional[str] = None,
):
    """
    get all blocks on notion page.
    Args:
        page_id (str): notion page_id to search
        token_path (str, optional): _description_. Defaults to RESEARCH_API_PATH.
        token (Optional[str], optional): _description_. Defaults to None.

    Returns:
        _type_: request response code (200 if succeeded) and response text, block_children
    """
    if not token:
        token = get_token(token_path)

    headers = {
        "Authorization": f"Bearer {token}",
        "Notion-Version": "2022-06-28",
    }

    api_url = f"https://api.notion.com/v1/blocks/{page_id}/children?page_size=100"

    # get block children from notion
    response = requests.get(api_url, headers=headers)

    try:
        block_children = response.json()["results"]
    except AttributeError:
        print("failed to get block children")
        block_children = None

    return response.status_code, response.text, block_children

find_database_on_page

find_database_on_page(page_id: str) -> Dict[str, str]

find all database on page.

Returns:

  • Dict[str, str]

    Dict[str, str]: dictionary whose keys are database ids and values are database names

Source code in ResearchToolkit/notion/block.py
def find_database_on_page(page_id: str) -> Dict[str, str]:
    """
    find all database on page.

    Returns:
        Dict[str, str]: dictionary whose keys are database ids and values are database names

    """
    _, _, block_children = retrieve_block_children(page_id)

    databases = dict()
    if block_children is None:
        return databases
    for block in block_children:
        if block["type"] == "child_database":
            database = {block["id"]: block["child_database"]["title"]}
            databases.update(database)
    return databases

append_block_children

append_block_children(page_id: str, block: Union[dict, List[dict]], token_path: str = RESEARCH_API_PATH, token: Optional[str] = None)

append block or blocks to a page

Parameters:

  • page_id (str) –

    description

  • block (Union[dict, List[dict]]) –

    output or list of outputs of Block objects e.g) Paragraph("hello world")() or [Heading1("Tutorial")(), Paragraph("hello world")()]

  • token_path (str, default: RESEARCH_API_PATH ) –

    description. Defaults to RESEARCH_API_PATH.

  • token (Optional[str], default: None ) –

    description. Defaults to None.

Returns:

  • _type_

    request response code (200 if succeeded) and response text

Source code in ResearchToolkit/notion/block.py
def append_block_children(
    page_id: str,
    block: Union[dict, List[dict]],
    token_path: str = RESEARCH_API_PATH,
    token: Optional[str] = None,
):
    """append block or blocks to a page

    Args:
        page_id (str): _description_
        block (Union[dict, List[dict]]): output or list of outputs of `Block` objects
                                         e.g) Paragraph("hello world")() or [Heading1("Tutorial")(), Paragraph("hello world")()]
        token_path (str, optional): _description_. Defaults to RESEARCH_API_PATH.
        token (Optional[str], optional): _description_. Defaults to None.

    Returns:
        _type_: request response code (200 if succeeded) and response text
    """
    if not token:
        token = get_token(token_path)

    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json",
        "Notion-Version": "2022-06-28",
    }

    api_url = f"https://api.notion.com/v1/blocks/{page_id}/children"

    if isinstance(block, dict):
        block = [block]
    data = {"children": block}
    data = json.dumps(data)

    response = requests.request("PATCH", api_url, headers=headers, data=data)

    return response.status_code, response.text