Open or create persistent storage with a unique `name` and optional `storage_class` (used to extend the default `Storage` based behavior). Each storage is isolated by name within the current origin (domain). If the storage doesn't exist, it will be created. If it does exist, it
(name="", storage_class=Storage)
| 205 | |
| 206 | |
| 207 | async def storage(name="", storage_class=Storage): |
| 208 | """ |
| 209 | Open or create persistent storage with a unique `name` and optional |
| 210 | `storage_class` (used to extend the default `Storage` based behavior). |
| 211 | |
| 212 | Each storage is isolated by name within the current origin (domain). |
| 213 | If the storage doesn't exist, it will be created. If it does exist, |
| 214 | its current contents will be loaded. |
| 215 | |
| 216 | This function returns a `Storage` instance (or custom subclass instance) |
| 217 | acting as a persistent dictionary. A `ValueError` is raised if `name` is |
| 218 | empty or not provided. |
| 219 | |
| 220 | ```python |
| 221 | from pyscript import storage |
| 222 | |
| 223 | |
| 224 | # Basic usage. |
| 225 | user_data = await storage("user-profile") |
| 226 | user_data["name"] = "Alice" |
| 227 | user_data["age"] = 30 |
| 228 | |
| 229 | # Multiple independent storages. |
| 230 | settings = await storage("app-settings") |
| 231 | cache = await storage("api-cache") |
| 232 | |
| 233 | # With custom Storage class. |
| 234 | class ValidatingStorage(Storage): |
| 235 | def __setitem__(self, key, value): |
| 236 | if not isinstance(key, str): |
| 237 | raise TypeError("Keys must be strings") |
| 238 | super().__setitem__(key, value) |
| 239 | |
| 240 | validated = await storage("validated-data", ValidatingStorage) |
| 241 | ``` |
| 242 | |
| 243 | Storage names are automatically prefixed with `"@pyscript/"` to |
| 244 | namespace them within IndexedDB. |
| 245 | """ |
| 246 | if not name: |
| 247 | raise ValueError("Storage name must be a non-empty string") |
| 248 | |
| 249 | underlying_store = await _polyscript_storage(f"@pyscript/{name}") |
| 250 | return storage_class(underlying_store) |
no outgoing calls