wopr 0.1.1
A high-performance async web framework built on Granian's RSGI interface
License: MIT
Requires Python: >=3.12
Keywords: web, framework, async, rsgi, granian, background-tasks

# WOPR Web Framework

A high-performance async web framework built specifically for Granian's RSGI interface. WOPR combines the developer experience of Flask/Quart with the performance benefits of RSGI.

## 🏁 Benchmarks

```
🧪 Testing WOPR Benchmark Endpoints
==================================================
✅ Info              1.98ms  application/json
✅ JSON              0.48ms  application/json
✅ Plaintext         0.37ms  text/plain
✅ Single Query      1.54ms  application/json
✅ 5 Queries         1.71ms  application/json
✅ 3 Updates         2.92ms  application/json
✅ Fortunes          2.76ms  text/html; charset=utf-8
✅ 10 Cached        12.31ms  application/json
```

## 🚀 Features

- **High Performance**: Built on Granian's RSGI interface for maximum speed
- **Async/Await**: Full async support throughout the framework
- **Background Tasks**: Intelligent task system with DuckDB storage and priorities
- **WebSocket Support**: Real-time communication with room management
- **Template Engine**: Jinja2 integration with async support
- **Middleware System**: Static files, CORS, security, and custom middleware
- **Security First**: CSRF protection, security headers, rate limiting
- **CLI Tools**: Project initialization and management commands
- **Developer Experience**: Clean APIs, helpful error messages, hot reload

## 📦 Installation

```bash
# Basic installation
uv add wopr

# With all features
uv add "wopr[all]"

# Or specific features
uv add "wopr[templates,tasks,cli]"
```

## 🏃 Quick Start

### Create a New Project
```bash
# Install WOPR with CLI tools
uv add "wopr[cli]"

# Create new project
uv run wopr init my_app

# Navigate and run
cd my_app
uv sync
granian --interface rsgi --reload app:app
```

### Simple Example
```python
from wopr import WOPR, Request, jsonify

app = WOPR(__name__)

@app.get("/")
async def hello(request: Request):
    return jsonify({"message": "Hello from WOPR!"})

@app.get("/users/<user_id>")
async def get_user(request: Request, user_id: str):
    return jsonify({"user_id": user_id, "name": f"User {user_id}"})

# Run with: granian --interface rsgi app:app
```

## 📚 Examples

### 🌟 Interactive Demo (`example_app.py`)
Complete showcase of all framework features with a web UI:
```bash
uv sync --extra all
granian --interface rsgi --reload example_app:app
```
Visit http://localhost:8000 for interactive demos of:
- HTTP endpoints and routing
- Background task processing
- WebSocket communication
- Security features
- Middleware functionality

### 📊 Data Handling (`data_example.py`)
RESTful API demonstrating data operations:
```bash
granian --interface rsgi --reload data_example:app
```
Features:
- CRUD operations with filtering and pagination
- Background data processing
- Real-time analytics
- Task monitoring

### 📈 Benchmarks (`benchmark_simple.py`)
Standard TechEmpower benchmark implementation:
```bash
granian --interface rsgi --workers 4 --threads 2 benchmark_simple:app
```
Benchmark endpoints:
- JSON serialization
- Database queries (simulated)
- Database updates (simulated)
- Plaintext response
- HTML template rendering
- Cached queries

## 🏗️ Architecture

```
src/wopr/
├── core/           # Main WOPR application class
├── http/           # Request/Response handling & routing  
├── websocket/      # WebSocket support & room management
├── tasks/          # Background task system with DuckDB
├── templates/      # Jinja2 template engine
├── middleware/     # Static files, CORS, security
├── cli/            # Command-line tools
└── utils/          # Rate limiting and utilities
```

## 🔧 Key Components

### Application
```python
from wopr import WOPR

app = WOPR(__name__)
app.init_templates()  # Enable Jinja2 templates

# Route decorators
@app.get("/")
@app.post("/api/data")  
@app.websocket("/ws")

# Middleware
from wopr.middleware import CORSMiddleware
app.add_middleware(CORSMiddleware(origins=["*"]))
```

### Background Tasks
```python
@app.task("send_email", "notifications")
async def send_email(to: str, subject: str):
    # Task implementation
    return {"status": "sent"}

# Queue tasks
task_id = await app.add_background_task(
    "send_email", "notifications", TaskPriority.HIGH,
    to="user@example.com", subject="Welcome!"
)

# Start workers
await app.start_task_workers("notifications", worker_count=2)
```

### WebSocket
```python
@app.websocket("/ws/chat")
async def chat_handler(websocket):
    await websocket.accept()
    
    while True:
        message = await websocket.receive()
        await websocket.send_text(f"Echo: {message.data}")
```

### Templates
```python
@app.get("/")
async def index(request):
    return await app.render_template("index.html", 
                                   message="Hello World!")
```

## 🛡️ Security

- **CSRF Protection**: Built-in CSRF token generation and validation
- **Security Headers**: X-Frame-Options, CSP, HSTS, etc.
- **Rate Limiting**: Configurable rate limiting with decorators
- **Input Validation**: Request data validation and sanitization
- **Static File Security**: Path traversal protection

## ⚡ Performance

- **RSGI Interface**: Maximum performance with Granian server
- **Async Throughout**: Non-blocking operations everywhere
- **Background Tasks**: Offload heavy work to background queues
- **Efficient Routing**: Fast path matching with parameter extraction
- **Optional Dependencies**: Load only what you need

## 🧪 Testing

```bash
# Install dev dependencies
uv sync --extra dev

# Run tests (when implemented)
uv run pytest

# Code quality
uv run black .          # Format code
uv run ruff check .     # Lint code  
uv run mypy src/        # Type checking
```

## 📖 Documentation

- **CLAUDE.md**: Comprehensive development guide
- **DATA_EXAMPLE.md**: Data handling tutorial
- **Example Applications**: Fully commented examples

## 🤝 Contributing

WOPR is built with modern Python best practices:
- **Python 3.12+** for latest async improvements
- **Type hints** throughout the codebase
- **Modular architecture** for easy extension
- **Comprehensive error handling**
- **Security-first design**

## 📄 License

MIT License - see LICENSE file for details.

## 🔗 Links

- **GitHub**: https://github.com/wopr-framework/wopr  
- **Documentation**: https://wopr-framework.readthedocs.io
- **PyPI**: https://pypi.org/project/wopr

---

**WOPR** - High-performance async web framework for modern Python web applications. 🎮