Add your description here
Project description
Nitro
โ ๏ธ Early Beta - This library is in active development and APIs may change.
Nitro is a collection of abstraction layers for Python web development. It is not a framework - it's a toolkit that works with your favorite web frameworks (FastAPI, Flask, FastHTML, Django, etc.).
Built on rusty-tags core, Nitro provides intelligent templating, reactive component support, event system, and a powerful Tailwind CSS CLI.
Three Core Abstraction Layers
- Active Record - Entity-centric persistence with rich domain models
- Front-end UI Design - High-performance HTML generation, reactive components, templating
- Event Routing - Domain events with Blinker, decoupled side effects
What Nitro Provides
- ๐ท๏ธ Complete HTML5/SVG Tags: All standard HTML5 and SVG elements powered by rusty-tags core
- โก High Performance: 3-10x faster than pure Python through Rust-optimized HTML generation
- ๐จ Modern Templating: Page templates, decorators, and component system for full-stack development
- ๐ Reactive Components: Built-in Datastar integration for modern web applications
- ๐๏ธ FastHTML-Style API: Familiar syntax with callable chaining support
- ๐ง Intelligent Processing: Automatic attribute handling and smart type conversion
- ๐ฏ Tailwind CSS CLI: CLI for Tailwind CSS integration and build management
- ๐ฆ Works Everywhere: Integrates with FastAPI, Flask, Django, FastHTML, and any Python web framework
Architecture
Nitro is built on top of the rusty-tags core package:
rusty-tags(core): High-performance HTML generation library with Rust backendnitro(abstraction layers): Collection of tools for web development - Active Record, UI Design, Event Routing
Quick Start
Installation
# Install Nitro (includes rusty-tags as dependency)
pip install nitro-boost
# For development - clone and install
git clone <repository>
cd nitro
pip install -e .
The installation includes the nitro CLI for Tailwind CSS management:
# Verify CLI installation
nitro --version
# See available commands
nitro --help
# Initialize Tailwind CSS in your project
nitro tw init
Core Features
๐ท๏ธ Complete HTML5/SVG Tag System
Nitro provides all standard HTML5 and SVG elements as Python functions:
# HTML elements
Html, Head, Body, Title, Meta, Link, Script
H1, H2, H3, H4, H5, H6, P, Div, Span, A
Form, Input, Button, Select, Textarea, Label
Table, Tr, Td, Th, Tbody, Thead, Tfoot
Nav, Main, Section, Article, Header, Footer
Img, Video, Audio, Canvas, Iframe
# ... and many more
# SVG elements
Svg, Circle, Rect, Line, Path, Polygon
G, Defs, Use, Symbol, LinearGradient
Text, Image, ForeignObject
# ... complete SVG support
๐จ Modern Templating System
Page Templates:
from nitro.utils import Page, page_template
# Complete HTML documents
page = Page(
H1("My Site"),
P("Content here"),
title="Page Title",
hdrs=(Meta(charset="utf-8"), Link(rel="stylesheet", href="/app.css")),
datastar=True # Auto-include Datastar reactive library
)
# Reusable templates with decorators
@page_template("My App", datastar=True)
def my_view():
return Div("Page content")
Component System:
# Reusable components
def Card(title, *content, **attrs):
return Div(
H3(title, cls="card-title"),
Div(*content, cls="card-body"),
cls="card",
**attrs
)
# Usage
cards = Div(
Card("Card 1", P("First card content")),
Card("Card 2", P("Second card content"), cls="featured"),
cls="card-grid"
)
โก Performance Optimizations
- Memory Pooling: Thread-local string pools and arena allocators
- Intelligent Caching: Lock-free attribute processing with smart cache invalidation
- String Interning: Common HTML strings pre-allocated for efficiency
- Type Optimization: Fast paths for common Python types and HTML patterns
- Expression Detection: Intelligent JavaScript expression analysis for reactive components
๐ Reactive Component Integration
Built-in Datastar support for modern reactive web development:
# Reactive state management
interactive_form = Form(
Input(bind="$email", placeholder="Enter email"),
Input(bind="$name", placeholder="Enter name"),
Button("Submit", on_click=DS.post("/api/submit", data={"email": "$email", "name": "$name"})),
Div(
text="Email: $email, Name: $name",
show="$email && $name" # Conditional display
),
signals={"email": "", "name": ""} # Initial state
)
# Server-sent events and real-time updates
@app.get("/updates")
async def live_updates():
async def event_stream():
while True:
yield SSE.patch_elements(
Div(f"Update: {datetime.now()}", cls="update"),
selector="#updates"
)
await asyncio.sleep(1)
return event_stream()
๐๏ธ FastHTML-Style API
Familiar syntax with enhanced capabilities:
# Traditional syntax
content = Div("Hello", cls="greeting")
# Callable chaining (FastHTML-style)
content = Div(cls="container")(
H1("Title"),
P("Content")
)
# Attribute flexibility
element = Div(
"Content",
{"id": "main", "data-value": 123}, # Dict automatically expands to attributes
cls="primary",
hidden=False # Boolean attributes handled correctly
)
๐ง Smart Type System
Intelligent handling of Python types:
# Automatic type conversion
Div(
42, # Numbers โ strings
True, # Booleans โ "true"/"false" or boolean attributes
None, # None โ empty string
[1, 2, 3], # Lists โ joined strings
custom_obj, # Objects with __html__(), render(), or _repr_html_()
)
# Framework integration
class MyComponent:
def __html__(self):
return "<div>Custom HTML</div>"
# Automatically recognized and rendered
Div(MyComponent())
๐ Auto-Routing System (Phase 2)
Nitro's auto-routing system dramatically reduces boilerplate by automatically generating RESTful routes from entity methods. Works with FastAPI, Flask, FastHTML, and other Python web frameworks.
Quick Example
from nitro.domain.entities.base_entity import Entity
from nitro.routing import action
from fastapi import FastAPI
from nitro.adapters.fastapi import configure_nitro
# Define entity with actions
class Counter(Entity, table=True):
count: int = 0
@action() # Automatically routed!
def increment(self, amount: int = 1) -> dict:
self.count += amount
self.save()
return {"count": self.count}
@action()
def reset(self) -> dict:
self.count = 0
self.save()
return {"count": 0}
# Configure app (one line!)
app = FastAPI()
configure_nitro(app, entities=[Counter])
# Routes automatically generated:
# POST /counter/{id}/increment?amount=5
# POST /counter/{id}/reset
Before Auto-Routing: 190 lines of boilerplate route handlers After Auto-Routing: < 50 lines of pure business logic
Custom Route Naming
Control your API design with custom entity names and action paths:
Custom Entity Names
Use __route_name__ for plural forms or custom naming:
class User(Entity):
__route_name__ = "users" # Plural form
username: str = ""
@action()
def activate(self):
self.is_active = True
self.save()
return {"status": "activated"}
# Generated URL: POST /users/{id}/activate (not /user/{id}/activate)
Custom Action Paths
Use @action(path="...") for cleaner URLs:
class BlogPost(Entity):
__route_name__ = "posts"
title: str = ""
is_published: bool = False
@action(path="/publish") # Custom path
def make_public(self):
self.is_published = True
self.save()
return {"status": "published"}
# Generated URL: POST /posts/{id}/publish (not /posts/{id}/make_public)
Combined Customization
class BlogPost(Entity):
__route_name__ = "posts" # Custom entity name
@action(path="/publish") # Custom action path
def make_public(self):
...
# Generated URL: POST /posts/{id}/publish
API Versioning with Prefixes
Support multiple API versions simultaneously:
# V1 API - Simple counter
configure_nitro(app, entities=[CounterV1], prefix="/api/v1")
# V2 API - Enhanced counter with new features
configure_nitro(app, entities=[CounterV2], prefix="/api/v2")
# Both versions coexist:
# POST /api/v1/counter/{id}/increment
# POST /api/v2/counter/{id}/increment
Features
- ๐ฏ Zero Boilerplate: Define business logic once, routes generated automatically
- ๐ Type Safety: Parameter extraction from type hints with Pydantic validation
- ๐จ Custom Naming: Full control over entity names and action paths
- ๐ฆ Works With Any Framework: Integrates with FastAPI, Flask, FastHTML, and more
- ๐ Plug & Play: One-line configuration per web framework
- ๐ OpenAPI: Automatic Swagger/ReDoc documentation (FastAPI)
- ๐ญ Versioning: API prefixes for versioning support
Try It
Run the interactive demo:
# Custom routing demo
uvicorn examples.custom_routes_demo:app --port 8095
# API versioning demo
uvicorn examples.versioned_api_demo:app --port 8090
Then visit http://localhost:8095/ for interactive documentation and examples.
Learn More
- ๐ Custom Route Naming Guide: Complete guide with examples
- ๐ Route Prefixes Guide: API versioning strategies
- ๐ฏ Phase 2 Design: Technical architecture
- ๐ก Examples: Working demo applications
โก Tailwind CSS CLI
Nitro includes a powerful CLI for Tailwind CSS integration that works with any Python web framework.
Quick Start
# Initialize Tailwind CSS in your project
nitro tw init
# Start development with file watching
nitro tw dev
# Build production CSS
nitro tw build
Features
- ๐ Works Everywhere: Integrates with FastAPI, Django, Flask, FastHTML, Sanic, and any Python web framework
- ๐ฆ Standalone Binary: Downloads and manages Tailwind CSS standalone CLI automatically
- โ๏ธ Smart Configuration: Auto-detects project structure with environment variable overrides
- ๐ File Watching: Development mode with automatic CSS rebuilding
- ๐ฏ Content Scanning: Scans your entire project for Tailwind classes
- ๐ง Zero Config: Works out of the box with sensible defaults
Commands
nitro tw init
Initialize Tailwind CSS in your project:
# Basic initialization
nitro tw init
# With detailed output
nitro tw init --verbose
# Force overwrite existing files
nitro tw init --force
What it does:
- Downloads the Tailwind CSS standalone binary for your platform
- Creates CSS input file with Tailwind v4 directives
- Sets up appropriate directory structure
- Updates
.gitignorewith generated file patterns
nitro tw dev
Start Tailwind CSS in watch mode for development:
# Start file watcher
nitro tw dev
# With detailed output
nitro tw dev --verbose
Features:
- Watches all project files for Tailwind class changes
- Automatically rebuilds CSS when changes detected
- Shows build progress and file sizes
- Graceful keyboard interrupt handling
nitro tw build
Build optimized production CSS:
# Build production CSS
nitro tw build
# Build with custom output path
nitro tw build --output dist/styles.css
# Build without minification
nitro tw build --no-minify
# Verbose build information
nitro tw build --verbose
Configuration
Auto-Detection
Nitro automatically detects the best CSS file locations based on your project structure:
# If static/ folder exists:
static/css/input.css โ static/css/output.css
# If assets/ folder exists:
assets/input.css โ assets/output.css
# Otherwise:
input.css โ output.css
Environment Variables
Override default paths using environment variables:
# Custom input CSS location
NITRO_TAILWIND_CSS_INPUT="src/styles/main.css"
# Custom output CSS location
NITRO_TAILWIND_CSS_OUTPUT="dist/app.css"
# Custom content scanning paths
NITRO_TAILWIND_CONTENT_PATHS='["src/**/*.py", "templates/**/*.html"]'
Environment Files
Create .env files in your project root for persistent configuration:
# .env
NITRO_TAILWIND_CSS_INPUT="assets/styles/input.css"
NITRO_TAILWIND_CSS_OUTPUT="public/css/styles.css"
# .env.local (for local development overrides)
NITRO_TAILWIND_CSS_OUTPUT="dev/styles.css"
# .env.prod (for production settings)
NITRO_TAILWIND_CSS_OUTPUT="dist/production.css"
Integration Examples
FastAPI
# Project structure
myapp/
โโโ static/css/
โโโ templates/
โโโ .env
โโโ main.py
# .env
NITRO_TAILWIND_CSS_INPUT="static/css/input.css"
NITRO_TAILWIND_CSS_OUTPUT="static/css/styles.css"
Django
# Project structure
myproject/
โโโ myapp/static/css/
โโโ templates/
โโโ .env
โโโ settings.py
# .env
NITRO_TAILWIND_CSS_INPUT="myapp/static/src/input.css"
NITRO_TAILWIND_CSS_OUTPUT="myapp/static/css/tailwind.css"
NITRO_TAILWIND_CONTENT_PATHS='["myapp/**/*.py", "templates/**/*.html"]'
Flask
# Project structure
flask-app/
โโโ static/css/
โโโ templates/
โโโ .env
โโโ app.py
# .env
NITRO_TAILWIND_CSS_INPUT="static/scss/main.css"
NITRO_TAILWIND_CSS_OUTPUT="static/css/app.css"
Binary Management
The CLI automatically manages the Tailwind CSS standalone binary:
- Download Location:
~/.nitro/cache/latest/tailwindcss-{platform}-{arch} - Version Support: Latest Tailwind CSS v4.x
- Platform Support: Windows, macOS (Intel/ARM), Linux (x64/ARM)
- Validation: Ensures downloaded binary is genuine Tailwind CLI
- Cache: Reuses downloaded binary across projects
Content Scanning
By default, Nitro scans these file patterns for Tailwind classes:
[
"**/*.py", # Python files
"**/*.html", # HTML templates
"**/*.jinja2", # Jinja templates
"!**/__pycache__/**", # Exclude Python cache
"!**/test_*.py" # Exclude test files
]
Customize scanning patterns with environment variables:
NITRO_TAILWIND_CONTENT_PATHS='[
"src/**/*.py",
"templates/**/*.html",
"components/**/*.vue",
"!**/node_modules/**"
]'
Integration with Development Servers
The Tailwind CLI runs independently of your web application, making it perfect for development workflows:
# Terminal 1: Start your web server
python -m uvicorn main:app --reload
# Terminal 2: Start Tailwind watcher
nitro tw dev
Or use process managers like honcho or foreman:
# Procfile
web: python -m uvicorn main:app --reload --port 8000
css: nitro tw dev
Troubleshooting
Binary Download Issues:
# Check binary location
ls -la ~/.nitro/cache/latest/
# Clear cache and re-download
rm -rf ~/.nitro/cache/ && nitro tw init
Configuration Issues:
# Test configuration loading
python -c "from nitro.config import get_nitro_config; print(get_nitro_config().tailwind.css_output)"
# Verify environment variables
env | grep NITRO_TAILWIND
Web Framework Integration Examples
FastAPI
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from nitro.utils import page_template
app = FastAPI()
page = page_template("My API", datastar=True)
@app.get("/")
@page(wrap_in=HTMLResponse)
def index():
return Main(H1("API Dashboard"))
Flask
from flask import Flask
from nitro import Page, H1, P
app = Flask(__name__)
@app.route("/")
def index():
return str(Page(
H1("Flask + Nitro"),
P("High performance templating"),
title="Flask Demo"
))
Jupyter/IPython
from nitro.utils import show
from nitro import Div, H1
# Display in notebooks
content = Div(H1("Notebook Content"), style="color: blue;")
show(content) # Renders directly in Jupyter cells
Documentation
Comprehensive documentation is available:
- ๐ Tutorial: Build a Todo app in 5 minutes
- ๐ API Reference: Complete API documentation
- ๐ Migration Guide: Migrate from StarModel
- ๐ Changelog: Version history and breaking changes
- ๐ก Examples: Complete working applications
Quick Start
# Install
pip install nitro-boost
# Follow 5-minute tutorial
# See docs/TUTORIAL.md
Development Requirements
For development and building from source:
- Python 3.10+: Core runtime
- Rust toolchain: Required for building RustyTags (HTML generation core)
- Install Rust: https://rustup.rs/
- Verify:
rustc --version
- Maturin: Python-Rust build tool
- Install:
pip install maturin
- Install:
# Clone and build
git clone <repository>
cd nitro
pip install -e .
License
MIT License - See LICENSE file for details.
Contributing
Contributions welcome! Please check the repository for contributing guidelines and open issues.
Links
- Repository: https://github.com/ndendic/Nitro
- Issues: https://github.com/ndendic/Nitro/issues
- Examples: See
examples/directory for complete applications
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file nitro_boost-0.2.5.tar.gz.
File metadata
- Download URL: nitro_boost-0.2.5.tar.gz
- Upload date:
- Size: 184.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.23
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6f60f0a5a1b7faf0952ecc11adfe139e6aec98cbd9ff41a5dfdac1b2ede2ec4e
|
|
| MD5 |
ee299dbfb41b05dbcc52e057a81733b0
|
|
| BLAKE2b-256 |
e7e46fe893c8111701d881fb9bc198ff48c4c37f915b826e0155a62ac9ac4942
|
File details
Details for the file nitro_boost-0.2.5-py3-none-any.whl.
File metadata
- Download URL: nitro_boost-0.2.5-py3-none-any.whl
- Upload date:
- Size: 221.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.8.23
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
ed5f3df8447b238f65fb05710d23d94e2ec7bf3319a236ff4dba9b9e73080a87
|
|
| MD5 |
eacc792f59ea0faf4d2aaab81e4f0ec4
|
|
| BLAKE2b-256 |
65eec74a3bc526ae4e8aefbca255ef2741820cf1d7e0ac159374753b5d9a79aa
|