Python-to-JavaScript transpiler that enables Python 3 development in web browsers with full DOM integration and standard library support
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Browser storage APIs including localStorage, sessionStorage, and IndexedDB with Python interfaces for persistent data management in web applications.
Persistent key-value storage that survives browser sessions and page reloads.
class LocalStorage:
"""
Interface to browser localStorage API.
"""
def __getitem__(self, key: str) -> str:
"""
Get item from localStorage.
Args:
key: Storage key
Returns:
Stored value as string
Raises:
KeyError: If key doesn't exist
"""
def __setitem__(self, key: str, value: str) -> None:
"""
Set item in localStorage.
Args:
key: Storage key
value: Value to store (converted to string)
"""
def __delitem__(self, key: str) -> None:
"""
Remove item from localStorage.
Args:
key: Storage key to remove
Raises:
KeyError: If key doesn't exist
"""
def __contains__(self, key: str) -> bool:
"""Check if key exists in localStorage."""
def __len__(self) -> int:
"""Get number of items in localStorage."""
def keys(self) -> list[str]:
"""Get all storage keys."""
def values(self) -> list[str]:
"""Get all storage values."""
def items(self) -> list[tuple[str, str]]:
"""Get all key-value pairs."""
def clear(self) -> None:
"""Clear all localStorage data."""
def get(self, key: str, default: str = None) -> str:
"""Get item with default value."""
def pop(self, key: str, default: str = None) -> str:
"""Remove and return item."""Usage:
from browser.local_storage import LocalStorage
import json
storage = LocalStorage()
# Basic operations
storage['username'] = 'john_doe'
storage['theme'] = 'dark'
username = storage['username'] # 'john_doe'
theme = storage.get('theme', 'light') # 'dark'
# Store complex data as JSON
user_data = {
'name': 'John Doe',
'email': 'john@example.com',
'preferences': {'theme': 'dark', 'language': 'en'}
}
storage['user_data'] = json.dumps(user_data)
# Retrieve and parse JSON
stored_data = json.loads(storage['user_data'])
print(stored_data['name']) # 'John Doe'
# Check existence and iterate
if 'settings' in storage:
print("Settings found")
for key in storage.keys():
print(f"{key}: {storage[key]}")
# Clean up
del storage['old_data']
storage.clear() # Remove all dataTemporary storage that persists only for the browser tab session.
class SessionStorage(LocalStorage):
"""
Interface to browser sessionStorage API.
Inherits all LocalStorage methods but data is session-scoped.
"""Usage:
from browser.session_storage import SessionStorage
session = SessionStorage()
# Temporary data that won't persist across browser restarts
session['temp_token'] = 'abc123'
session['form_draft'] = json.dumps({
'title': 'Draft Article',
'content': 'Work in progress...'
})
# Data available only in current tab/window
temp_token = session.get('temp_token')
# Will be cleared when tab/window closesAdvanced database storage for large amounts of structured data with indexing and transactions.
class IndexedDB:
"""
Interface to browser IndexedDB API for structured data storage.
"""
def __init__(self, name: str, version: int = 1):
"""
Initialize IndexedDB connection.
Args:
name: Database name
version: Database version number
"""
def open(self) -> None:
"""Open database connection."""
def close(self) -> None:
"""Close database connection."""
def delete_database(self) -> None:
"""Delete entire database."""
def transaction(self, stores: list[str], mode: str = 'readonly') -> 'Transaction':
"""
Create database transaction.
Args:
stores: List of object store names
mode: Transaction mode ('readonly', 'readwrite')
Returns:
Transaction object
"""
def create_object_store(self, name: str, options: dict = None) -> 'ObjectStore':
"""
Create object store (table).
Args:
name: Store name
options: Store configuration (keyPath, autoIncrement, etc.)
Returns:
ObjectStore object
"""
class Transaction:
"""Database transaction for atomic operations."""
def objectStore(self, name: str) -> 'ObjectStore':
"""Get object store from transaction."""
def abort(self) -> None:
"""Abort transaction."""
def commit(self) -> None:
"""Commit transaction (usually automatic)."""
class ObjectStore:
"""Object store for data operations."""
def add(self, value: Any, key: Any = None) -> None:
"""Add new record."""
def put(self, value: Any, key: Any = None) -> None:
"""Add or update record."""
def get(self, key: Any) -> Any:
"""Get record by key."""
def delete(self, key: Any) -> None:
"""Delete record by key."""
def clear(self) -> None:
"""Clear all records."""
def count(self) -> int:
"""Count records."""
def getAll(self, query: Any = None) -> list[Any]:
"""Get all records matching query."""
def getAllKeys(self) -> list[Any]:
"""Get all keys."""
def create_index(self, name: str, keyPath: str, options: dict = None) -> 'Index':
"""Create index for faster queries."""Usage:
from browser.indexed_db import IndexedDB, EventListener
# Database setup
class UserDB:
def __init__(self):
self.db = IndexedDB('UserDatabase', 1)
self.setup_database()
def setup_database(self):
def on_upgrade_needed(event):
# Create object stores during upgrade
users_store = self.db.create_object_store('users', {
'keyPath': 'id',
'autoIncrement': True
})
# Create indexes
users_store.create_index('email', 'email', {'unique': True})
users_store.create_index('name', 'name')
listener = EventListener()
listener.bind('upgradeneeded', on_upgrade_needed)
self.db.open()
def add_user(self, user_data):
"""Add new user to database."""
transaction = self.db.transaction(['users'], 'readwrite')
users_store = transaction.objectStore('users')
def on_success(event):
print(f"User added with ID: {event.target.result}")
def on_error(event):
print(f"Error adding user: {event.target.error}")
request = users_store.add(user_data)
request.bind('success', on_success)
request.bind('error', on_error)
def get_user(self, user_id):
"""Get user by ID."""
transaction = self.db.transaction(['users'], 'readonly')
users_store = transaction.objectStore('users')
def on_success(event):
user = event.target.result
if user:
display_user(user)
else:
print("User not found")
request = users_store.get(user_id)
request.bind('success', on_success)
def find_user_by_email(self, email):
"""Find user by email using index."""
transaction = self.db.transaction(['users'], 'readonly')
users_store = transaction.objectStore('users')
email_index = users_store.index('email')
def on_success(event):
user = event.target.result
if user:
print(f"Found user: {user['name']}")
else:
print("No user with that email")
request = email_index.get(email)
request.bind('success', on_success)
# Usage
user_db = UserDB()
# Add users
user_db.add_user({
'name': 'John Doe',
'email': 'john@example.com',
'age': 30,
'created': str(datetime.now())
})
# Retrieve users
user_db.get_user(1)
user_db.find_user_by_email('john@example.com')Generic storage interface for managing Python objects with automatic serialization.
class ObjectStorage:
"""
High-level storage interface for Python objects.
"""
def __init__(self, storage_type: str = 'local'):
"""
Initialize object storage.
Args:
storage_type: 'local', 'session', or 'indexed'
"""
def store(self, key: str, obj: Any) -> None:
"""
Store Python object.
Args:
key: Storage key
obj: Object to store (will be serialized)
"""
def retrieve(self, key: str) -> Any:
"""
Retrieve and deserialize object.
Args:
key: Storage key
Returns:
Deserialized Python object
"""
def remove(self, key: str) -> None:
"""Remove stored object."""
def exists(self, key: str) -> bool:
"""Check if object exists."""
def list_keys(self) -> list[str]:
"""List all storage keys."""Usage:
from browser.object_storage import ObjectStorage
storage = ObjectStorage('local')
# Store complex objects
user_profile = {
'id': 123,
'name': 'Jane Smith',
'settings': {
'theme': 'dark',
'notifications': True,
'language': 'en'
},
'history': ['page1', 'page2', 'page3']
}
storage.store('user_profile', user_profile)
# Retrieve objects
profile = storage.retrieve('user_profile')
print(profile['settings']['theme']) # 'dark'
# Manage storage
if storage.exists('user_profile'):
print("Profile found")
for key in storage.list_keys():
print(f"Stored object: {key}")
storage.remove('old_data')Intelligent caching system with expiration and size management.
class CacheManager:
"""
Advanced caching with expiration and size limits.
"""
def set(self, key: str, value: Any, ttl: int = None) -> None:
"""
Set cached value with optional TTL.
Args:
key: Cache key
value: Value to cache
ttl: Time to live in seconds
"""
def get(self, key: str) -> Any:
"""Get cached value (None if expired/missing)."""
def invalidate(self, key: str) -> None:
"""Remove cached value."""
def clear_expired(self) -> None:
"""Remove all expired cache entries."""
def clear_all(self) -> None:
"""Clear entire cache."""
def get_stats(self) -> dict:
"""Get cache statistics."""Usage:
from browser.storage import CacheManager
cache = CacheManager()
# Cache API responses with TTL
def fetch_user_data(user_id):
cache_key = f'user_{user_id}'
# Check cache first
cached_data = cache.get(cache_key)
if cached_data:
print("Using cached data")
return cached_data
# Fetch from API if not cached
def on_success(req):
user_data = req.json
# Cache for 5 minutes
cache.set(cache_key, user_data, ttl=300)
return user_data
ajax = Ajax()
ajax.bind('complete', on_success)
ajax.open('GET', f'/api/users/{user_id}')
ajax.send()
# Periodic cache cleanup
from browser.timer import set_interval
def cleanup_cache():
cache.clear_expired()
stats = cache.get_stats()
print(f"Cache: {stats['size']} items, {stats['expired']} expired")
# Clean up every 10 minutes
set_interval(cleanup_cache, 600000)import json
from datetime import datetime
def serialize_data(data):
"""Convert complex data types for storage."""
if isinstance(data, datetime):
return data.isoformat()
elif hasattr(data, '__dict__'):
return data.__dict__
return data
def deserialize_data(data):
"""Restore complex data types from storage."""
if isinstance(data, str) and 'T' in data:
try:
return datetime.fromisoformat(data)
except:
pass
return datadef check_storage_quota():
"""Check available storage space."""
try:
# Test storage availability
test_key = '__storage_test__'
storage[test_key] = 'x' * 1024 # 1KB test
del storage[test_key]
return True
except:
print("Storage quota exceeded")
return False
def cleanup_old_data():
"""Remove old data to free space."""
current_time = datetime.now().timestamp()
for key in list(storage.keys()):
if key.startswith('temp_'):
try:
data = json.loads(storage[key])
if 'timestamp' in data:
age = current_time - data['timestamp']
if age > 86400: # 24 hours
del storage[key]
except:
# Remove corrupted data
del storage[key]This comprehensive storage system provides persistent data management capabilities for Brython applications, from simple key-value storage to complex database operations with indexing and transactions.
Install with Tessl CLI
npx tessl i tessl/pypi-brython