pystak 1.1.0
A modern, high-performance Python web framework with advanced features
License: MIT
Requires Python: >=3.8
Keywords: web, framework, async, python, api, rest, microservice

# PyStak - Modern Python Web Framework

[![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://python.org)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Build Status](https://img.shields.io/badge/build-passing-brightgreen.svg)](https://github.com/pystak/pystak)

PyStak is a modern, high-performance Python web framework designed for building APIs and web applications with advanced features out of the box.

## 🚀 Features

- **Async-First**: Built from the ground up with async/await support
- **Dependency Injection**: Advanced DI system with automatic resolution
- **Type Safety**: Full type hints and validation support
- **Middleware System**: Powerful middleware with built-in security features
- **Advanced Routing**: Path parameters, type conversion, and route groups
- **Auto-Validation**: Request/response validation with custom schemas
- **Performance**: High-performance ASGI server with built-in optimizations
- **Developer Experience**: Rich CLI tools and project scaffolding
- **Production Ready**: Built-in monitoring, logging, and error handling

## 📦 Installation

```bash
pip install pystak
```

For development with all features:
```bash
pip install pystak[all]
```

## 🏃 Quick Start

### 1. Create a new project

```bash
pystak new myproject
cd myproject
pip install -r requirements.txt
```

### 2. Basic Application

```python
from pystak import PyStak, JSONResponse

app = PyStak()

@app.get("/")
async def home():
    return {"message": "Hello, PyStak!"}

@app.get("/users/<int:user_id>")
async def get_user(user_id: int):
    return {"user_id": user_id, "name": f"User {user_id}"}

if __name__ == "__main__":
    app.run(debug=True)
```

### 3. Run the application

```bash
python main.py
# or
pystak run
```

Visit `http://localhost:8000` to see your application!

## 📚 Core Concepts

### Routing

PyStak provides advanced routing with type conversion and path parameters:

```python
from pystak import PyStak

app = PyStak()

# Basic routes
@app.get("/")
async def home():
    return {"message": "Home"}

@app.post("/users")
async def create_user():
    return {"message": "User created"}

# Path parameters with type conversion
@app.get("/users/<int:user_id>")
async def get_user(user_id: int):
    return {"user_id": user_id}

@app.get("/posts/<slug:post_slug>")
async def get_post(post_slug: str):
    return {"slug": post_slug}

# Route groups
api = app.group("/api/v1")

@api.get("/health")
async def health():
    return {"status": "healthy"}
```

### Dependency Injection

PyStak includes a powerful dependency injection system:

```python
from pystak import PyStak, Depends, Injectable

@Injectable
class UserService:
    async def get_user(self, user_id: int):
        return {"id": user_id, "name": f"User {user_id}"}

app = PyStak()

@app.get("/users/<int:user_id>")
async def get_user(user_id: int, user_service: UserService = Depends()):
    return await user_service.get_user(user_id)
```

### Request Handling

Advanced request handling with automatic parsing:

```python
from pystak import PyStak, Request

app = PyStak()

@app.post("/upload")
async def upload_file(request: Request):
    # JSON data
    json_data = await request.json()
    
    # Form data
    form_data = await request.form()
    
    # File uploads
    files = await request.files()
    
    # Query parameters
    page = request.get_query_param("page", "1")
    
    return {"received": "ok"}
```

### Validation

Built-in validation with custom schemas:

```python
from pystak import PyStak, validate_json, Schema, FieldValidator, TypeValidator, EmailValidator
from dataclasses import dataclass

# Using dataclass validation
@dataclass
class User:
    name: str
    email: str
    age: int = 0

@app.post("/users")
@validate_json(User)
async def create_user(validated_data: User):
    return {"user": validated_data}

# Using schema validation
user_schema = Schema({
    'name': FieldValidator([TypeValidator(str)], required=True),
    'email': FieldValidator([EmailValidator()], required=True),
    'age': FieldValidator([TypeValidator(int)], default=0)
})

@app.post("/users-alt")
@validate_json(user_schema)
async def create_user_alt(validated_data: dict):
    return {"user": validated_data}
```

### Middleware

Powerful middleware system with built-in security:

```python
from pystak import PyStak, Middleware, Request
from pystak.middleware import CORSMiddleware, SecurityHeadersMiddleware

app = PyStak()

# Built-in middleware
app.middleware(CORSMiddleware(allow_origins=["*"]))
app.middleware(SecurityHeadersMiddleware())

# Custom middleware
class LoggingMiddleware(Middleware):
    async def process_request(self, request: Request, call_next):
        print(f"Request: {request.method} {request.path}")
        response = await call_next()
        print(f"Response: {response.status_code}")
        return response

app.middleware(LoggingMiddleware)
```

### Configuration

Advanced configuration management:

```python
from pystak import Config

# Load from files and environment
config = Config([
    "config/development.yaml",
    "config/production.yaml"
], env_prefix="MYAPP_")

# Get configuration values with type conversion
database_url = config.get("database_url", type_hint=str)
debug_mode = config.get("debug", False, type_hint=bool)
max_connections = config.get("max_connections", 10, type_hint=int)
```

## 🛠️ CLI Tools

PyStak includes powerful CLI tools for development:

```bash
# Create new project
pystak new myproject --template api

# Run development server
pystak run --reload --debug

# Generate code
pystak generate route /api/users --methods GET POST
pystak generate middleware auth
pystak generate model User --fields name:str email:str age:int
```

## 🏗️ Project Templates

### Basic Template
Simple web application with basic routing.

### API Template
RESTful API with authentication, CORS, and structured services.

### Full Template
Complete application with database, caching, Docker, and production configuration.

## 📖 Advanced Features

### WebSocket Support
```python
@app.websocket("/ws")
async def websocket_endpoint(websocket):
    await websocket.accept()
    while True:
        data = await websocket.receive_text()
        await websocket.send_text(f"Echo: {data}")
```

### Background Tasks
```python
from pystak import BackgroundTasks

@app.post("/send-email")
async def send_email(background_tasks: BackgroundTasks):
    background_tasks.add_task(send_email_task, "user@example.com")
    return {"message": "Email queued"}
```

### Database Integration
```python
from pystak.database import Database

database = Database("postgresql://user:pass@localhost/db")

@app.on_startup
async def startup():
    await database.connect()

@app.on_shutdown
async def shutdown():
    await database.disconnect()
```

## 🔧 Configuration

### Environment Variables
```bash
PYSTAK_DEBUG=true
PYSTAK_HOST=0.0.0.0
PYSTAK_PORT=8000
PYSTAK_DATABASE_URL=postgresql://localhost/mydb
```

### Configuration Files
```yaml
# config/development.yaml
debug: true
database_url: "sqlite:///dev.db"
redis_url: "redis://localhost:6379"
secret_key: "dev-secret"

cors:
  allow_origins: ["*"]
  allow_methods: ["GET", "POST", "PUT", "DELETE"]
```

## 🧪 Testing

```python
import pytest
from pystak.testing import TestClient

@pytest.fixture
def client():
    return TestClient(app)

def test_home(client):
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"message": "Hello, PyStak!"}

async def test_async_endpoint(client):
    response = await client.get("/async-endpoint")
    assert response.status_code == 200
```

## 🚀 Deployment

### Docker
```dockerfile
FROM python:3.11-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
EXPOSE 8000

CMD ["python", "main.py"]
```

### Production Server
```bash
# Using Gunicorn
gunicorn main:app -w 4 -k uvicorn.workers.UvicornWorker

# Using Uvicorn
uvicorn main:app --host 0.0.0.0 --port 8000 --workers 4
```

## 📊 Performance

PyStak is built for performance:

- **High Throughput**: Handles thousands of requests per second
- **Low Latency**: Minimal overhead with async processing
- **Memory Efficient**: Optimized memory usage with connection pooling
- **Scalable**: Horizontal scaling with multiple workers

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## 📄 License

PyStak is licensed under the MIT License. See [LICENSE](LICENSE) for details.

## 🙏 Acknowledgments

PyStak is inspired by modern web frameworks and built with the Python community in mind. Special thanks to:

- FastAPI for async patterns
- Flask for simplicity
- Django for comprehensive features
- Starlette for ASGI foundation

## 📞 Support

- **Documentation**: [https://pystak.dev/docs](https://pystak.dev/docs)
- **Issues**: [GitHub Issues](https://github.com/pystak/pystak/issues)
- **Discussions**: [GitHub Discussions](https://github.com/pystak/pystak/discussions)
- **Discord**: [PyStak Community](https://discord.gg/pystak)

---

**Built with ❤️ by the PyStak Team**