Share your JupyterLite Examples

For now, you need this bit of magic that I’ve included in some of my examples above;

# From https://gist.github.com/bollwyvl/132aaff5cdb2c35ee1f75aed83e87eeb
async def get_contents(path):
    """use the IndexedDB API to acess JupyterLite's in-browser (for now) storage
    
    for documentation purposes, the full names of the JS API objects are used.
    
    see https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest
    """
    import js, asyncio

    DB_NAME = "JupyterLite Storage"

    # we only ever expect one result, either an error _or_ success
    queue = asyncio.Queue(1)
    
    IDBOpenDBRequest = js.self.indexedDB.open(DB_NAME)
    IDBOpenDBRequest.onsuccess = IDBOpenDBRequest.onerror = queue.put_nowait
    
    await queue.get()
    
    if IDBOpenDBRequest.result is None:
        return None
        
    IDBTransaction = IDBOpenDBRequest.result.transaction("files", "readonly")
    IDBObjectStore = IDBTransaction.objectStore("files")
    IDBRequest = IDBObjectStore.get(path, "key")
    IDBRequest.onsuccess = IDBRequest.onerror = queue.put_nowait
    
    await queue.get()
    
    return IDBRequest.result.to_py() if IDBRequest.result else None

If you put that in the top cell of your notebook (and run it first), then you can access the contents of an “uploaded” (to the browser storage) file named “my_file.csv” (as a str object) with;

csv_str = (await get_contents("my_file.csv"))["content"]

Or if you need a file object you can wrap that in io.StringIO. e.g.

file_obj = io.StringIO((await get_contents("my_file.csv"))["content"])
2 Likes