Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support adding a row from a template #266

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions notion/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
from getpass import getpass
from time import sleep

from .block import Block, BLOCK_TYPES
from .collection import (
Expand Down Expand Up @@ -373,7 +374,46 @@ def create_record(self, table, parent, **kwargs):
)

return record_id

def get_task_status(self, task_id):
"""
Get a status of a single task
"""
data = self.post(
"getTasks",
{
"taskIds": [task_id]
}
).json()
Comment on lines +382 to +387
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
data = self.post(
"getTasks",
{
"taskIds": [task_id]
}
).json()
data = self.post("getTasks", dict(taskIds=[task_id]).json()


results = data.get("results")
if results is None:
return None

if not results:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is the same with

if results is None:

Or something I don't know =)

# Notion does not know about such a task
print("Invalid task ID.")
return None

if len(results) == 1:
state = results[0].get("state")
return state

return None
Comment on lines +398 to +402
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if len(results) == 1:
state = results[0].get("state")
return state
return None
try:
task = results.pop()
return task.get("state", None)
except IndexError:
logger.error("There is no task {}".format(results))
return None


def wait_for_task(self, task_id, interval=1, tries=10):
"""
Wait for a task by looping 'tries' times ever 'interval' seconds.
The 'interval' parameter can be used to specify milliseconds using double (e.g 0.75).
"""
for i in range(tries):
state = self.get_task_status(task_id)
if state in ["not_started", "in_progress"]:
sleep(interval)
elif state == "success":
return state

print("Task takes more time than expected. Specify 'interval' or 'tries' to wait more.")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
print("Task takes more time than expected. Specify 'interval' or 'tries' to wait more.")
logger.debug("Task takes more time than expected. Specify 'interval' or 'tries' to wait more.")


class Transaction(object):

Expand Down
28 changes: 27 additions & 1 deletion notion/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,14 +186,40 @@ def get_schema_property(self, identifier):
return prop
return None

def add_row(self, update_views=True, **kwargs):
def add_row(self, update_views=True, source_block=None, **kwargs):
"""
Create a new empty CollectionRowBlock under this collection, and return the instance.
Specify 'source_block' to create a row from a template block.
"""

row_id = self._client.create_record("block", self, type="page")
row = CollectionRowBlock(self._client, row_id)

# User wants to create a row from a template
if source_block:
# The source block can be either an ID or a URL
source_block = self._client.get_block(source_block)
# Start a duplication task
data = self._client.post(
"enqueueTask",
{
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i would rather use dict() instead of {}, especially when the keys are constants (not variables). But this decision up to @jamalex

"task": {
"eventName": "duplicateBlock",
"request": {
"sourceBlockId": source_block.id,
"targetBlockId": row_id,
"appendContentOnly": True
}
}
},
).json()

task_id = data.get("taskId")

if task_id:
# Wait until the duplication task finishes
self._client.wait_for_task(task_id)

with self._client.as_atomic_transaction():
for key, val in kwargs.items():
setattr(row, key, val)
Expand Down