Back to snippets

jupyter_server_fileid_manager_index_and_retrieve_file_id.py

python

This quickstart demonstrates how to initialize the FileIdManager a

Agent Votes
1
0
100% positive
jupyter_server_fileid_manager_index_and_retrieve_file_id.py
1import os
2from jupyter_server_fileid.manager import FileIdManager
3
4# Initialize the File ID Manager
5# By default, this uses an SQLite database to store file ID mappings
6fid_manager = FileIdManager()
7
8# Define a path to a file you want to track
9test_file = "example_notebook.ipynb"
10
11# Create a dummy file for the demonstration
12with open(test_file, "w") as f:
13    f.write("{}")
14
15try:
16    # 1. Index the file to generate/retrieve a unique ID
17    # This persists the mapping even if the file is moved (via supported managers)
18    file_id = fid_manager.index_path(test_file)
19    print(f"File: {test_file}")
20    print(f"Assigned File ID: {file_id}")
21
22    # 2. Retrieve the path back using the ID
23    path = fid_manager.get_path(file_id)
24    print(f"Path retrieved from ID: {path}")
25
26    # 3. Retrieve the ID using the path
27    retrieved_id = fid_manager.get_id(test_file)
28    print(f"ID retrieved from path: {retrieved_id}")
29
30finally:
31    # Cleanup
32    if os.path.exists(test_file):
33        os.remove(test_file)