Metadata-Version: 2.4
Name: axion-framework
Version: 0.1.0a1
Summary: axion is a lightweight, modular, and fast web framework implemented in Python using sockets. It provides a modern implementation of the HTTP protocol, allowing users to build and run web applications with ease, supporting both API and SSR.
Project-URL: Homepage, https://github.com/sachin-acharya-projects/axion
Project-URL: Bug Tracker, https://github.com/sachin-acharya-projects/axion/issues
Author-email: Sachin Acharya <sachin.acharya@axion.com>
License: MIT
License-File: LICENSE
Keywords: API,Pydantic,PythonFramework,SSR,WebFramework,Webserver
Classifier: Development Status :: 3 - Alpha
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.12
Requires-Dist: colorama>=0.4.6
Requires-Dist: jinja2>=3.1.3
Requires-Dist: pydantic>=2.6.4
Requires-Dist: python-dotenv>=1.0.0
Requires-Dist: watchdog>=6.0.0
Provides-Extra: db
Requires-Dist: sqlalchemy>=2.0; extra == 'db'
Provides-Extra: dev
Requires-Dist: hatchling>=1.21.0; extra == 'dev'
Requires-Dist: mypy>=2.1.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: ruff>=0.3.0; extra == 'dev'
Requires-Dist: sqlalchemy>=2.0; extra == 'dev'
Requires-Dist: twine>=6.2.0; extra == 'dev'
Description-Content-Type: text/markdown

# axion - Lightweight & Fast Python Web Framework

[![Version](https://img.shields.io/pypi/v/axion-framework)](https://pypi.org/project/axion-framework/)
[![License](https://img.shields.io/badge/license-MIT-green)](./LICENSE)

## Overview

**axion** is a lightweight, modular, and fast web framework implemented in Python using native sockets. Designed for both simplicity and performance, axion provides a modern approach to building web applications, supporting both **Server-Side Rendering (SSR)** with Jinja2 and **Asynchronous API** development with Pydantic.

Whether you're building a simple static site or a complex data-driven API, axion gives you the tools you need without the bloat of larger frameworks.

---

## Features

### 🚀 Core Capabilities

- **Native Socket Implementation**: Built from the ground up using Python's `socket` module for maximum control and minimal overhead.
- **High Concurrency**: Multi-threaded request handling over a high-backlog TCP server (64 worker threads, backlog 128).
- **Advanced Routing**: Regex-based path matching with type-safe parameter extraction (e.g., `/user/<int:id>`).
- **Async Route Handlers**: FastAPI-style `async def` handlers with a dedicated event loop per request.
- **Static File Serving**: Built-in support for serving CSS, JS, images, and other assets with security-first path resolution.

### 🛡️ Security & Modern Web

- **CSRF Protection**: Built-in Cross-Site Request Forgery protection for all non-idempotent methods (POST, PUT, DELETE, PATCH).
- **CORS Support**: Configurable Cross-Origin Resource Sharing for API security.
- **Pydantic Integration**: Seamless data validation and serialization. Simply type-hint a Pydantic model in your handler, and axion handles the rest.
- **Graceful Termination**: Full support for system signals (`SIGINT`, `SIGTERM`) to ensure no connections or resources are leaked on shutdown.

### 🛠️ Developer Experience

- **Scaffold CLI**: Generate a complete project structure in seconds with `axion startproject`.
- **Hot Reloading**: Automatic server restarts during development when code changes are detected.
- **Modular Architecture**: Decoupled App, Router, and Server components allow for highly portable and testable code.
- **UI Component System**: A hierarchical Python UI system (similar to Flutter or JSX) for building frontend structures directly in Python code.

---

## Installation

You can install axion using `pip`:

```bash
pip install axion-framework
```

Database/ORM support is an optional extra; install it when you plan to use
`app.use_database()`:

```bash
pip install "axion-framework[db]"
```

For development, clone the repository and install dependencies:

```bash
git clone https://github.com/sachin-acharya-projects/axion.git
cd axion
make dev-install
```

---

## Documentation

The full user guide lives in [`docs/`](docs/README.md). It starts with an
overview and a table of contents, then covers each topic in its own page:

| Topic | What you'll learn |
| ----- | ----------------- |
| [Getting Started](docs/getting-started.md) | Install, scaffold, first routes |
| [Routing](docs/routing.md) | Path parameters, methods, error handlers, routers |
| [Request & Response](docs/request-response.md) | The request/response API, JSON, headers, cookies |
| [Middleware](docs/middleware.md) | Callable and hook-object middleware, scoping |
| [Database & ORM](docs/database.md) | Models, sessions, transactions, injection |
| [Serializers](docs/serializers.md) | DRF-style input/output serialization |
| [Templates & Static Files](docs/templates-static.md) | Jinja2 rendering, static assets |
| [Security](docs/security.md) | CSRF and CORS |
| [Configuration](docs/configuration.md) | Every setting and how to override it |
| [Command-Line Interface](docs/cli.md) | `startproject`, `run`, hot reload |

A complete worked example is in [`example/`](example/).

---

## Quick Start

### 1. Create a Project

Use the CLI to generate a new project:

```bash
axion startproject my_app
cd my_app
```

### 2. Define Your Application

Edit `main.py`:

```python
from axion import WebServer
from axion.http import Response
from pydantic import BaseModel

app = WebServer(debug=True)

class User(BaseModel):
    name: str
    age: int

# SSR Route
@app.route("/")
def index(response: Response):
    response.render("index.html", title="Welcome to axion")

# API Route with Pydantic validation
@app.route("/api/user", methods=["POST"])
def create_user(user: User, response: Response):
    return response.json({"message": f"Hello {user.name}", "received": user.model_dump()})

if __name__ == "__main__":
    app.run()
```

### 3. Run with Hot Reload

```bash
axion run main.py --reload
```

---

## Middleware

Middleware runs in registration order around your routes. Two styles are
supported and can be mixed freely.

### Callable middleware

A plain function taking `(request, response, call_next)`. Do work before and
after `call_next()`:

```python
@app.use()
def timing(request, response, call_next):
    start = time.monotonic()
    call_next()
    print(f"{request.path} took {time.monotonic() - start:.3f}s")
```

### Hook middleware

Subclass `BaseMiddleware` and override `before_request` / `after_request`.
Returning early with a response from `before_request` short-circuits the
request:

```python
from axion.middleware import BaseMiddleware

class AuthMiddleware(BaseMiddleware):
    def before_request(self, request, response):
        if not request.headers.get("authorization"):
            response.send("Unauthorized", 401)   # skips the route

app.use(AuthMiddleware())
```

### Scoping

- **Global** — `app.use(mw)` runs for every request.
- **Path-scoped** — `app.use("/api", mw)` runs for `/api` and `/api/...`
  (prefix matching, so `/apix` is excluded).
- **Per-route** — `@app.route("/users", middleware=[mw])` runs only for that
  route.
- **Methods** — `app.use(mw, methods=["POST"])` restricts a middleware to
  specific HTTP methods. Hook objects may declare `methods` on the class.

```python
app.use("/api", auth_middleware, methods=["POST", "PUT", "DELETE"])
```

---

## Database & ORM

axion ships out-of-the-box SQLAlchemy support through the `axion[db]` extra.
You never touch the engine or session factory; a request-scoped session is
managed for you and committed (or rolled back) automatically.

### Define models

```python
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column

from axion.db import Model

class User(Model):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(100))
```

### Enable the database

```python
from axion import WebServer

app = WebServer(debug=True)
app.use_database()   # uses DATABASE_URL (default: sqlite:///db.sqlite3)
```

Tables are created automatically (`AUTO_CREATE_TABLES`). Set `DATABASE_URL`
in `config/settings.py` to use another database, e.g.
`DATABASE_URL = "postgresql+psycopg://user:pass@localhost/db"`.

### Use the session

Handlers can request a `Session` directly — it is injected from the
request-scoped session and committed/rolled back at the end of the request:

```python
from sqlalchemy.orm import Session

@app.route("/users", methods=["POST"])
def create_user(user: UserCreate, session: Session, response: Response):
    session.add(User(**user.model_dump()))
    response.json({"ok": True}, 201)
```

---

## Configuration

axion uses a `settings.py` file (typically in a `config/` directory) for centralized configuration:

```python
import os
from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent.parent

# Server
HOST = "127.0.0.1"
PORT = 5500
DEBUG = True

# Security
CORS_ALLOWED_ORIGINS = ["*"]
CSRF_COOKIE_NAME = "axion_csrf"

# Directories
TEMPLATE_DIRS = "views"
STATIC_DIRS = ["static"]
```

---

## Project Structure

A typical axion project looks like this:

```text
.
├── config/
│   └── settings.py
├── static/
│   ├── css/
│   ├── js/
│   └── imgs/
├── views/
│   └── index.html
├── main.py
└── .env
```

---

## Development

Use the included `Makefile` for common development tasks:

- `make install`: Install the package.
- `make dev-install`: Install with development dependencies.
- `make lint`: Run Ruff for linting.
- `make format`: Run Ruff for formatting.
- `make build`: Build the distribution packages.
- `make publish`: Build and publish to PyPI.

---

## License

This project is licensed under the MIT License. See the [LICENSE](./LICENSE) file for details.

## Contact

For inquiries or support:

- Email: [sachin.acharya@axion.com](mailto:sachin.acharya@axion.com)
- GitHub: [sachin-acharya-projects](https://github.com/sachin-acharya-projects/)
