Search code examples
python-3.xnotion-apinotion

Python Notion-client Database Updates


I have a notion database that contains a list of file directories. I am writing a script that is going to update the names of all the files in that database so it will also need to update the filepaths in the database to reflect the new filenames.

Database layout: Filepath | File_name (currently correct) | Additional Info

At present I have a function that reads in the data from filepath and file name and passes that through to a rename function that will rename the old file name with the one that is in the database. so /example/_test_example.mp4 would become /example/example_file.mp4 with example_file.mp4 being the value that was in the filename column.

client=Client(auth=NOTION_TOKEN)
db_info=client.databases.retrieve(database_id=files_db)
rows=client.databases.query(database_id=files_db)
content_ids=[]
for row in rows['results']:
    file_name=row['properties']['File_name']['rich_text'][0]['plain_text']
    filepath=row['properties']['Filepath']['title'][0]['plain_text']
    update_filename(file_name,filepath)

This code works as expected, getting both the filename and file path from the database. The rename function also works as expected so I wont bother posting that function here. It just replaces the current filename with the file name from the notion db using os.rename() and then passes the new filepath and the filename (passing the file name since I assume I am going to need to match the database row using it).

The code I have for updating the database is:

def update_db(video_file,new_file):    
    client.databases.update({
        "database_id": files_db,
        "properties":{
            'filepath': {'title': [{'text': {'content': filepath}}]},
        }
    })
    pprint('record inserted')

I know the update code wont work because I haven't been able to find out to do the "update x where y=y". Running it as it is I get the error that the database ID argument is missing. For writing to the database in the first place I used the client.pages.create(**{}).

Does anyone have an example of how the database update function should work? I did take a look at the notion api documentation, but I cant figure out how to implement that into using the notion-client package.


Solution

  • If you're trying to update a property value for certain rows in a db, I had to use a for loop with:

    client.pages.update(page_id= id, properties=update_data)     
    

    Each row when you queried the db should have an id and that is the page_id. My update_data was changing the date to a 'new_date':

    update_data = {"Assigned Date": {"date": {"start": new_date, "end": None}}}
    
    for index, row in df.iterrows():
        id = row['id']
        client.pages.update(page_id= pageID, properties=update_data)
        print(f"Updated page with ID {id}")