Skip to main content

Nexus Framework

An expressive, batteries-included, asynchronous web framework for Python, bringing the developer ergonomics, convention-over-configuration mindset, and rapid application development of Laravel to modern Python.


Architecture & Features

  • Dual-Mode ASGI Engine: Async-first performance with transparent support for synchronous handlers.
  • IoC Container & Auto-Wiring: Type-hinted dependency injection, singleton management, and circular dependency protection.
  • Service Providers: Two-phase (register and boot) modular service lifecycle.
  • Context-Safe Facades: Static-like access (App, Route, DB, Auth) powered by Python's contextvars for safe concurrent request isolation.
  • Eloquent-style Active Record: Fluent query builder and models backed by SQLAlchemy Core.
  • Artisan-inspired CLI: Code generators (make:*), dev server (serve), and interactive shell (tinker).

Installation & Development Setup

Clone the repository and set up your Python 3.12+ virtual environment:

# Create virtual environment
python -m venv .venv

# Activate virtual environment
# Windows:
.\.venv\Scripts\Activate.ps1
# Unix/macOS:
source .venv/bin/activate

# Install in editable mode with development dependencies
pip install -e ".[dev]"

Running Quality Checks & Tests

# Run test suite
pytest

# Run static type checking
mypy src

# Run linter and formatting checks
ruff check src tests

Core Usage Examples

1. Inversion of Control (IoC) Container & Auto-Wiring

from nexus.container import Container

container = Container()

class Database:
    pass

class UserRepository:
    def __init__(self, db: Database) -> None:
        self.db = db

# Register singleton
container.singleton(Database)

# Auto-wires Database into UserRepository automatically
repo = container.make(UserRepository)
assert isinstance(repo.db, Database)

2. Service Provider Lifecycle

from nexus.application import Application
from nexus.foundation.provider import ServiceProvider

class AppServiceProvider(ServiceProvider):
    def register(self) -> None:
        # Register services & bindings
        self.app.singleton("payment_gateway", lambda app: StripeGateway())

    def boot(self) -> None:
        # Execute startup configurations
        pass

app = Application(base_path=".")
app.register_provider(AppServiceProvider)
app.boot_providers()

3. Context-Safe Facades & Config

from nexus.facades import App, Config, Log
from nexus.support.env import env

# Type-cast environment variable
debug_mode = env("APP_DEBUG", False)

# Static access to configuration and application
app_name = Config.get("app.name", "Nexus")
Config.set("app.env", "production")

# Static logging
Log.info("Application configured and ready")

4. Dual-Mode Handler Runner (Sync & Async)

from nexus.foundation.runner import HandlerRunner

runner = HandlerRunner()

# Automatically awaits asynchronous coroutines on event loop
async def async_handler():
    return {"mode": "async"}

# Automatically offloads synchronous functions to worker threadpool
def sync_handler():
    return {"mode": "sync"}

await runner.run(async_handler)
await runner.run(sync_handler)

5. Fluent Routing & Route Groups

from nexus.facades import Route

# Basic routes with parameter regex constraints
Route.get("/users/{id}", lambda id: {"user_id": id}).where_number("id")

# Route groups with shared prefix and middleware
Route.group({"prefix": "api/v1"}, lambda: [
    Route.get("/status", lambda: {"active": True}),
    Route.post("/posts", lambda: {"created": True}),
])

# RESTful resource routing
Route.resource("photos", PhotoController)

6. Declarative Form Requests & Input Validation

from pydantic import BaseModel
from nexus.http.requests import FormRequest

class UserSchema(BaseModel):
    name: str
    email: str
    age: int

class StoreUserRequest(FormRequest):
    def rules(self):
        return UserSchema

# Type-hinted in controller: automatically validates before executing!
def store(form: StoreUserRequest):
    data = form.validated()
    return {"user": data["name"]}

7. Middleware Pipeline & Rate Limiting

from nexus.http.middleware import Middleware
from nexus.routing.throttle import ThrottleRequests

class SecurityHeadersMiddleware(Middleware):
    async def handle(self, request, next_handler):
        response = await next_handler(request)
        response.header("X-Frame-Options", "DENY")
        return response

# Attach route-level rate limiting (e.g. 60 requests per minute)
Route.get("/api/data", lambda: {"data": []}).middleware(
    ThrottleRequests(max_attempts=60, decay_seconds=60)
)

8. Eloquent Active Record Models & Relationships

from typing import ClassVar
from nexus.database.models import Model, SoftDeletes
from nexus.database.models.relations import BelongsTo, HasMany

class Post(Model):
    fillable: ClassVar[list[str]] = ["user_id", "title", "content"]

    def user(self) -> BelongsTo:
        return self.belongs_to(User, "user_id", "id")

class User(Model, SoftDeletes):
    fillable: ClassVar[list[str]] = ["name", "email", "is_admin"]
    casts: ClassVar[dict[str, str]] = {"is_admin": "bool"}

    def posts(self) -> HasMany:
        return self.has_many(Post, "user_id", "id")

    @classmethod
    def scope_admins(cls, query):
        query.where("is_admin", True)

# Eloquent CRUD API
user = User.create(name="Taylor", email="taylor@example.com", is_admin=True)
admins = User.query().admins().latest().get()

# Eager loading (eliminating N+1 query problems)
authors = User.query().with_("posts").get()
first_user_posts = authors[0].posts

9. Database Migrations, Schema Builder & Query Builder

from nexus.facades import DB, Schema
from nexus.database.migrations import Migration
from nexus.database.schema import Blueprint

# Fluent Query Builder
active_users = (
    DB.table("users")
    .where("votes", ">", 100)
    .order_by("votes", "desc")
    .paginate(per_page=15)
)

# Schema Migration DSL
class CreateArticlesTable(Migration):
    def up(self) -> None:
        def table_definition(table: Blueprint) -> None:
            table.id()
            table.foreign_id("user_id")
            table.string("title")
            table.text("body").nullable()
            table.timestamps()
            table.soft_deletes()

        Schema.create("articles", table_definition)

    def down(self) -> None:
        Schema.drop_if_exists("articles")

10. Artisan-Style CLI & Code Scaffolding

Nexus provides a rich, Typer-powered and Rich-styled command-line toolchain for code generation, database management, and development inspection:

# Display help and all available commands
python nexus.py --help
# or via installed entrypoint:
nexus --help

# Code Scaffolding (make:*)
nexus make:controller UserController --resource
nexus make:model Post -m -f -s # creates model, migration, factory, and seeder
nexus make:migration create_orders_table --create=orders
nexus make:middleware VerifyApiKey
nexus make:request StorePostRequest
nexus make:provider PaymentServiceProvider
nexus make:command SendWeeklyDigest
nexus make:policy PostPolicy

# Database Management
nexus migrate                 # Run pending migrations
nexus migrate:rollback        # Rollback last migration batch
nexus migrate:reset           # Rollback all migrations
nexus migrate:refresh --seed  # Reset and re-run all migrations with seeders
nexus migrate:fresh --seed    # Drop all tables and re-run migrations
nexus migrate:status          # Status table of all migrations
nexus db:seed                 # Run DatabaseSeeder

# Development & Inspection
nexus serve --host 127.0.0.1 --port 8000  # Start dev server with hot reload
nexus route:list                          # Colorized table of routes, verbs, and middleware
nexus tinker                              # Interactive REPL with pre-booted kernel and models
nexus clear:cache                         # Clear application cache
nexus config:clear                        # Reset configuration caches
nexus route:clear                         # Reset route definitions

11. Programmatic Artisan Facade & Custom Commands

Custom CLI commands can be defined fluently in routes/console.py or as Command classes in app/console/commands/:

from nexus.facades import Artisan
from nexus.console import Command

# In routes/console.py
@Artisan.command("inspire", help="Display an inspiring quote")
def inspire() -> None:
    print("Simplicity is prerequisite for reliability. -- Edsger W. Dijkstra")

# Programmatic command execution (e.g. in test suites or deployment hooks)
Artisan.call("migrate")
Artisan.call("clear:cache")

# Subclassing the Command base class
class BackupCommand(Command):
    name = "backup:run"
    description = "Run database backup"

    def handle(self) -> None:
        self.info("Starting backup...")
        # Backup logic
        self.success("Backup completed successfully!")

12. Session Management & Flash Data

Nexus includes pluggable session drivers (memory, file, database) with anti-session fixation and flash data:

from nexus.facades import Session

# Set and retrieve session data
Session.put("user_id", 42)
user_id = Session.get("user_id")

# Flash data available only for the subsequent request
Session.flash("status", "Profile updated successfully!")

# Check existence & pull
if Session.has("status"):
    message = Session.pull("status")

# Regenerate session ID (prevent session fixation on login)
Session.regenerate(destroy_old=True)

13. Security Middleware (CSRF, CORS, Security Headers)

Comprehensive security protection out-of-the-box:

from nexus.security.csrf import VerifyCsrfToken
from nexus.security.cors import CorsMiddleware
from nexus.security.headers import SecurityHeadersMiddleware

# CSRF verification with wildcard exclusions
csrf = VerifyCsrfToken(except_uris=["api/*", "stripe/webhook"])

# CORS preflight and origin verification
cors = CorsMiddleware(
    allowed_origins=["https://myapp.com"],
    allowed_methods=["GET", "POST", "PUT", "DELETE"],
    allow_credentials=True,
)

# OWASP security headers (HSTS, X-Frame-Options, X-Content-Type-Options)
headers_middleware = SecurityHeadersMiddleware(frame_options="DENY")

14. Authentication, User Providers & Password Hashing

Multi-guard authentication supporting both stateful sessions and stateless API tokens:

from nexus.facades import Auth, Hash

# Password hashing with PBKDF2-HMAC-SHA256 (600,000 rounds) or Bcrypt
hashed_password = Hash.make("secret-password")
assert Hash.check("secret-password", hashed_password)

# Attempt web login using credentials
if Auth.attempt({"email": "admin@example.com", "password": "password123"}):
    current_user = Auth.user()
    user_id = Auth.id()

# Check authentication state
if Auth.check():
    print(f"Logged in as {Auth.user().email}")
elif Auth.guest():
    print("Welcome Guest")

# Stateless token guard for API endpoints
api_user = Auth.guard("api").user()

# Logout
Auth.logout()

15. Authorization Gates & Policies

Define custom authorization abilities and policies:

from nexus.facades import Gate

# Define an inline gate
Gate.define("edit-settings", lambda user: user.is_admin)

# Assign a policy class to an Eloquent model
class PostPolicy:
    def update(self, user, post) -> bool:
        return user.id == post.user_id

Gate.policy(Post, PostPolicy)

# Check permissions
if Gate.allows("update", post):
    post.update(title="New Title")
else:
    # Denied
    Gate.authorize("update", post)  # raises ForbiddenHttpException (403)

16. Blade-Style View Engine & Jinja2 Integration

Write clean templates using familiar Laravel Blade directives precompiled into Jinja2:

<!-- resources/views/layouts/app.html -->
<!DOCTYPE html>
<html>
<head>
    <title>@yield('title', 'My Application')</title>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body>
    @auth
        <p>Welcome, {{ user.name }}!</p>
    @guest
        <a href="/login">Sign In</a>
    @endauth

    <div class="content">
        @yield('content')
    </div>
</body>
</html>
<!-- resources/views/posts/create.html -->
@extends('layouts.app')

@section('title', 'Create Post')

@section('content')
<form method="POST" action="/posts">
    @csrf
    @method('POST')
    <input type="text" name="title" placeholder="Post Title">
    <button type="submit">Submit</button>
</form>
@endsection

Render views effortlessly using the global view() helper or View facade:

from nexus.view import view

@Route.get("/posts/create")
def create_post():
    return view("posts.create", {"active": True})

17. Background Jobs, Queues & Worker Daemons

Nexus provides unified asynchronous queues (sync, memory, database, redis):

from nexus.queue import Job
from nexus.facades import Queue

class SendVerificationEmail(Job):
    tries = 3
    backoff = 5  # wait 5s between retries

    def __init__(self, user_id: int) -> None:
        super().__init__(user_id)
        self.user_id = user_id

    def handle(self) -> None:
        print(f"Sending verification email to user: {self.user_id}")

# Fluent asynchronous dispatch
SendVerificationEmail.dispatch(user_id=42).on_queue("emails").delay(60)

# Run queue worker via Artisan CLI
# nexus queue:work --queue=emails --sleep=3

18. Task Scheduling & Cron Workflows

Define scheduled tasks in code without writing manual cron entries:

from nexus.facades import Schedule

# Artisan commands
Schedule.command("backup:run").daily().at("02:00").without_overlapping()

# Python callables
Schedule.call(lambda: print("Pruning expired tokens...")).every_five_minutes()

# Shell commands
Schedule.exec("node scripts/generate-sitemap.js").weekly().sundays().at("03:30")

# Run scheduler worker via Artisan CLI
# nexus schedule:run
# nexus schedule:work --sleep=60

19. Event Dispatcher & Queued Observers

Decouple application workflows with synchronous and background queued listeners:

from nexus.facades import Event
from nexus.queue import ShouldQueue

class OrderShipped:
    def __init__(self, order_id: int) -> None:
        self.order_id = order_id

# Queued listener runs in background automatically
class SendShippingNotification(ShouldQueue):
    def handle(self, event: OrderShipped) -> None:
        print(f"Notification sent for Order #{event.order_id}")

# Register & dispatch
Event.listen(OrderShipped, SendShippingNotification)
Event.dispatch(OrderShipped(order_id=1024))

20. Cache Repository, Tags & Atomic Locks

High-performance cache layer (memory, file, redis):

from nexus.facades import Cache

# Basic cache
Cache.put("user_42", {"name": "Alice"}, ttl=3600)
user = Cache.get("user_42")

# Remember (cache or compute)
stats = Cache.remember("dashboard_stats", 300, lambda: {"views": 15000})

# Cache Tags
Cache.tags("reports", "financials").put("q3", {"profit": 250000})
Cache.tags("reports").flush()  # Flushes all tagged entries

# Atomic Locks (concurrency control)
with Cache.lock("heavy_data_import", seconds=120) as acquired:
    if acquired:
        print("Importing safely without race conditions!")

21. Mail, Mailables & Multi-Channel Notifications

Deliver emails using SMTP, File, or Array transports:

from nexus.facades import Mail, Notification
from nexus.mail import Mailable
from nexus.notifications import Notification as BaseNotification

class OrderInvoiceMail(Mailable):
    subject = "Your Invoice"

    def __init__(self, order) -> None:
        super().__init__()
        self.order = order

    def build(self) -> None:
        self.view("emails.invoice", {"order": self.order})
        self.attach("invoice.pdf", b"...pdf_bytes...", "application/pdf")

# Send email immediately or queue to background
Mail.to("customer@example.com").send(OrderInvoiceMail(order))
Mail.to("customer@example.com").queue(OrderInvoiceMail(order))

# Multi-channel notification (Mail + Database)
class OrderStatusUpdated(BaseNotification):
    def via(self, notifiable):
        return ["mail", "database"]

    def to_mail(self, notifiable):
        return OrderInvoiceMail(notifiable.order)

Notification.send(customer, OrderStatusUpdated())

22. Filesystem & Storage Disks

Local and virtual cloud storage disks:

from nexus.facades import Storage

# Write and read files
Storage.put("avatars/1.png", image_bytes)
content = Storage.get("avatars/1.png")

# File inspection and public URLs
if Storage.exists("avatars/1.png"):
    file_url = Storage.url("avatars/1.png")  # /storage/avatars/1.png
    size_bytes = Storage.size("avatars/1.png")

# Copy, move, delete
Storage.copy("avatars/1.png", "backup/1.png")
Storage.delete("avatars/1.png")

23. Testing Framework & HTTP TestClient

Nexus provides a fluent, lightning-fast in-memory testing client (TestClient) and rich assertion wrapper (TestResponse):

from nexus.testing import TestCase

class UserApiTest(TestCase):
    def test_user_retrieval(self) -> None:
        # Fluent request chaining
        res = self.client.get("/api/v1/users", params={"page": 1})

        # Fluent status, header, and JSON assertions
        res.assert_ok() \
           .assert_header("content-type", "application/json") \
           .assert_json({"total": 25}) \
           .assert_json_path("data.0.name", "John Doe")

    def test_validation_errors(self) -> None:
        # Submit invalid payload
        res = self.client.post("/api/v1/users", json={"name": "Alice"})

        # Fluent validation assertions
        res.assert_status(422) \
           .assert_invalid(["email"]) \
           .assert_valid(["name"]) \
           .assert_json_validation_errors(["email"])

    def test_authenticated_route(self) -> None:
        user = User.find(1)
        res = self.acting_as(user).get("/api/v1/profile")
        res.assert_ok().assert_see("Welcome back")

Generate new test cases using Artisan:

nexus make:test UserApiTest        # Creates tests/feature/test_user_api.py (subclasses TestCase with self.client)
nexus make:test CalculatorTest --unit # Creates tests/unit/test_calculator.py (isolated unittest.TestCase)

24. Facade Fakes & Time Travel

Test complex distributed systems, logs, and async queues with zero mocks boilerplate:

from nexus.facades import Event, Queue, Mail, Notification, Storage, Log
from nexus.testing import travel_to, freeze_time

def test_order_fulfillment():
    # 1. Fake application facades
    Event.fake()
    Queue.fake()
    Mail.fake()
    Storage.fake()
    Log.fake()

    # 2. Time Travel
    with travel_to("2026-01-01 12:00:00"):
        process_order(order_id=42)

    # 3. Assertions
    Event.assert_dispatched(OrderPlaced)
    Queue.assert_pushed("GenerateInvoicePdfJob")
    Mail.assert_sent(OrderConfirmationMail)
    Storage.assert_exists("invoices/42.pdf")
    Log.assert_logged("info", lambda msg: "Order 42 processed" in msg)

25. Official Starter Kits & OpenAPI Swagger

Scaffold production-ready application architectures instantly with Artisan:

# Generate API Starter (Sanctum tokens, JSON resources, and OpenAPI Swagger UI)
nexus make:starter api

# Generate Web Starter (Session auth, Blade views, Tailwind CSS v4, Alpine.js, and Vite)
nexus make:starter web

# Generate Inertia Starter (Modern SPA with React, Tailwind CSS v4, and Vite)
nexus make:starter inertia
  • Nexus API Starter: Interactive Swagger documentation automatically generated at /api/docs and schema at /api/openapi.json.
  • Nexus Web Starter: Full authentication UI with Blade views (login.blade.html, register.blade.html, dashboard.blade.html), Tailwind CSS v4 styling, Alpine.js reactivity, and Vite NPM asset bundling (@vite(['resources/css/app.css', 'resources/js/app.js'])) with zero CDN reliance.
  • Nexus Inertia Starter: Reactive Single-Page Application (SPA) powered by React/Vue, @inertia layout, Tailwind CSS v4 (@import "tailwindcss";), and Python Nexus backend.

26. Fluent Collections (Collection & collect())

Chainable, expressive array and dictionary transformations inspired by Laravel Collections:

from nexus.support import collect

users = collect([
    {"id": 1, "name": "Alice", "role": "admin", "score": 90},
    {"id": 2, "name": "Bob", "role": "user", "score": 75},
    {"id": 3, "name": "Charlie", "role": "admin", "score": 85},
])

# Pluck, filter, and sort
names = users.where("role", "admin").sort_by("score", descending=True).pluck("name").all()
# ["Alice", "Charlie"]

# Aggregates and grouping
avg_score = users.avg("score")  # 83.33
grouped = users.group_by("role")  # {"admin": Collection([...]), "user": Collection([...])}

27. String & Array Helpers (Str, Stringable, Arr)

Rich text manipulation and nested dictionary dot-notation utilities:

from nexus.support import Str, str_helper, Arr

# Static and fluent string manipulation
slug = Str.slug("Nexus Web Framework 2026!")  # "nexus-web-framework-2026"
snake = Str.snake("UserProfileView")          # "user_profile_view"
uuid_str = Str.uuid()
masked = Str.mask("secretpassword", "*", 3, 6) # "sec******sword"

# Fluent Stringable chaining
title = str_helper("  my_post_title  ").trim().headline().value() # "My Post Title"

# Nested dictionary dot-notation traversal
payload = {"app": {"server": {"port": 8000}}}
port = Arr.get(payload, "app.server.port", 3000) # 8000
Arr.set(payload, "app.server.ssl", True)
exists = Arr.has(payload, "app.server.ssl")       # True

28. Fluent Datetime Engine (Carbon & Date Facade)

Laravel Carbon-equivalent fluent datetime manipulation:

from nexus.facades import Date
from nexus.support import Carbon

# Instantiation & Parsing
now = Date.now()
parsed = Date.parse("2026-10-26 14:30:00")

# Chainable Arithmetic & Boundaries
future = now.add_days(7).start_of_day()
month_end = now.end_of_month()

# Expressive Human Diffing
two_hours_ago = now.sub_hours(2).diff_for_humans() # "2 hours ago"
next_week = now.add_days(5).diff_for_humans()       # "in 5 days"

29. Standalone Validation Engine (Validator)

Validate data using standard Laravel pipe syntax rules, custom messages, and custom extensions:

from nexus.facades import Validator

validator = Validator.make(
    data={"email": "dev@nexus.test", "age": 28, "password": "secret", "password_confirmation": "secret"},
    rules={
        "email": "required|email",
        "age": "required|integer|between:18,99",
        "password": "required|min:6|confirmed",
    },
    messages={
        "email": "Please provide a valid corporate email address.",
    }
)

if validator.fails():
    errors = validator.errors().to_dict() # {"email": [...], ...}
else:
    validated_data = validator.validated()

30. Multi-Channel Logging (LogManager & Log Facade)

Structured, channel-based logging supporting daily rotation and contextual tags:

from nexus.facades import Log

# Log to default or specific channel
Log.info("User registered successfully", context={"user_id": 42})
Log.channel("daily").warning("Disk space low")
Log.stack(["single", "daily"]).critical("Database connection timeout")

# Contextual logging
Log.share_context(request_id="req-12345", ip="127.0.0.1")
# All subsequent logs in this async context automatically include request_id and ip!

31. Global Exception Handler (ExceptionHandler)

Unified exception reporting and response rendering for web and API requests:

from nexus.exceptions.handler import ExceptionHandler
from nexus.facades import App

handler: ExceptionHandler = App.make("exception.handler")

# Custom reportable and renderable handlers
handler.reportable(PaymentGatewayError, lambda exc: send_slack_alert(exc))
handler.renderable(PaymentGatewayError, lambda req, exc: JsonResponse({"error": "Payment failed"}, status_code=402))
  • API Requests: Automatically returns clean JSON responses ({"message": "...", "errors": {...}, "status": 422}).
  • Web Requests: Automatically renders dark-mode styled HTML error pages (404, 403, 419, 500) and rich debug stack traces when app.debug=True.

32. API Resources & Collections (JsonResource & ResourceCollection)

Transform Eloquent models and paginated datasets into structured JSON API responses:

from nexus.http.resources import JsonResource, ResourceCollection

class UserResource(JsonResource):
    def to_array(self, request=None):
        return {
            "id": self.id,
            "name": self.name.title(),
            "email": self.email,
        }

# Single resource
return UserResource(user).additional({"meta": {"version": "v1"}})

# Collection with automatic pagination metadata & links
return UserResource.collection(User.paginate(15))

33. URL Generator & Signed Routes (URL Facade & route())

Generate URLs for named routes, HMAC-SHA256 tamper-proof signed links, and expiration checks:

from nexus.facades import URL
from nexus.support import route

# Named route URL generation
profile_url = route("users.show", id=42, tab="security")
# "http://localhost:8000/users/42?tab=security"

# Temporary signed route with 30-minute expiration
signed_url = URL.signed_route("unsubscribe", {"user_id": 10}, expiration=1800)
# "http://localhost:8000/unsubscribe/10?expires=1730000000&signature=abc123def..."

# In route handler / middleware
if not request.has_valid_signature():
    abort(403, "Invalid or expired signature.")

34. Active Record State Tracking & Lifecycle

Inspect model dirty state, retrieve original values, reload from database, or touch timestamps:

user = User.find(1)
user.name = "New Name"

user.is_dirty()        # True
user.is_dirty("name")  # True
user.is_dirty("email") # False
user.get_dirty()       # {"name": "New Name"}
user.get_original("name") # "Old Name"

user.refresh()         # Discards memory modifications, reloads from database
user.touch()           # Updates updated_at timestamp immediately

35. Object-Oriented Validation Rules (Rule)

Create encapsulated, reusable validation rule objects:

from nexus.validation import Rule, Validator

class UppercaseRule(Rule):
    def passes(self, attribute, value) -> bool:
        return isinstance(value, str) and value.isupper()

    def message(self) -> str:
        return "The :attribute must be completely uppercase."

validator = Validator.make(
    data={"code": "promo2026"},
    rules={"code": ["required", UppercaseRule()]},
)

36. Artisan Scaffolding Generator Suite

Accelerate development with built-in Artisan generator commands:

nexus make:controller UserController --api
nexus make:model Post -mfs             # Model + Migration + Factory + Seeder
nexus make:job ProcessPaymentJob
nexus make:event OrderShipped
nexus make:listener SendShipmentEmail --event=OrderShipped --queued
nexus make:mail WelcomeMail
nexus make:notification NewMessageNotification
nexus make:rule ValidTaxIdentifier
nexus make:resource UserResource
nexus make:test UserFeatureTest
nexus sanctum:install                  # Scaffold personal access tokens migration

37. Nexus Sanctum: API Token Authentication

Issue and verify lightweight, SHA-256 hashed personal access tokens with granular abilities and expiration:

from nexus.database.models import Model
from nexus.auth import Authenticatable, HasApiTokens
from nexus.auth.sanctum import CheckAbilities

class User(Model, Authenticatable, HasApiTokens):
    table = "users"
    fillable = ["name", "email", "password"]

# 1. Create a personal access token (returns plain text token only once)
token_res = user.create_token(
    name="mobile-app",
    abilities=["orders:create", "orders:read"],
    expires_at=Date.now().add_days(30),
)
print(token_res.plain_text_token)  # "1|4f9b20..."

# 2. Check token abilities
user.token_can("orders:create")  # True
user.token_can("orders:delete")  # False

# 3. Protect routes with ability middlewares
@router.post("/orders", action=OrderController.store, middleware=[CheckAbilities("orders:create")])

38. Nexus Inertia.js Adapter

Build modern Single Page Apps using React, Vue, or Svelte without building a separate REST API:

from nexus.inertia import inertia, Inertia
from nexus.facades import Route

# 1. Global shared data (e.g. current user, flash notifications)
Inertia.share("auth", lambda: {"user": request.user.to_dict() if request.user else None})

# 2. Render Inertia component in controller / route
@router.get("/dashboard")
def dashboard(request):
    return inertia("Dashboard/Index", {
        "metrics": {"total_revenue": 95000, "active_users": 1420},
        "recent_orders": Inertia.lazy(lambda: Order.latest().take(10).get()),
    })

# 3. Automatic asset versioning & external redirection
Inertia.version("v1.0.4")
Inertia.location("https://external-auth.example.com")

In your Blade layout (resources/views/app.blade.php):

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    @inertiaHead
</head>
<body>
    @inertia
</body>
</html>

39. Faker Integration in Model Factories

Generate realistic mock data and test fixtures with automatic Faker bindings, states, and sequences:

from nexus.database.factory import Factory
from app.models.user import User

class UserFactory(Factory[User]):
    model = User

    def definition(self):
        return {
            "name": self.faker.name(),
            "email": self.faker.email(),
            "address": self.faker.address(),
            "is_admin": False,
        }

# 1. In-memory instances or persisted database records
mock_user = UserFactory.new().make()
saved_user = UserFactory.new().create()

# 2. State transformations & sequential attributes
admin_users = (
    UserFactory.new(count=5)
    .state({"is_admin": True})
    .sequence(lambda idx: {"email": f"admin_{idx + 1}@company.com"})
    .create()
)

# 3. Direct spawning from Model
new_users = User.factory().count(10).create()

40. Nexus Telescope & In-Browser Debugbar

Inspect real-time request metrics, database queries, memory usage, latency, and logs directly in your browser:

# config/app.py
return {
    "debug": True,
}

When debug mode is active:

  • Floating In-Browser Debugbar: Automatically rendered at the bottom of HTML responses with badges for Status (200 OK), Duration (3.4 ms), Memory (1.8 MB), Query count, and Route name.
  • Query Inspector: Expand the Queries tab to inspect exact SQL strings, parameter bindings, and query timings.
  • Dedicated Web Dashboard: Visit http://localhost:8000/telescope for historical request telemetry.
  • JSON Telemetry API: Available at /telescope/api/requests for headless SPA inspection.

Query telemetry programmatically via the Telescope facade:

from nexus.facades import Telescope

recent_requests = Telescope.entries(limit=50)

32. Fully Configurable Architecture (Laravel-Parity Configuration)

Nexus features a zero-boilerplate, deeply configurable environment and configuration system with full Laravel parity:

# Publish official framework configuration files (app, database, auth, session, logging, cache, queue, mail, telescope, cors)
nexus config:publish all

# Publish a specific configuration file
nexus config:publish database

# Create a custom application configuration
nexus make:config payment

# Clear and reload configuration caches
nexus config:clear

.env Environment Variables & env() Helper

Environment variables are automatically loaded and typed:

from nexus.support.env import env

# Automatically casts "true"/"false" to bool, "null" to None, ints, and floats
db_host = env("DB_HOST", "127.0.0.1")
debug_mode = env("APP_DEBUG", False)

config/*.py Dot-Notation Traversal & Config Facade

Every file in config/ is automatically mounted under its filename:

from nexus.facades import Config
from nexus.support import config

# Access via dot-notation
db_default = config("database.default")  # "sqlite"
app_name = Config.get("app.name", "Nexus")

# Runtime mutation
Config.set("app.debug", True)

In Blade templates, use the config() helper directly:

<title>{{ config('app.name', 'Nexus') }}</title>

Project Roadmap

See ROADMAP.md for detailed architectural decisions, milestone tracking, and phase-by-phase implementation plans.

Metadata

Release files for nexus-framework 0.4.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for nexus-framework 0.4.7
File Size Uploaded Provenance Actions
nexus_framework-0.4.7.tar.gz 293.3 kB Without provenance Details for nexus_framework-0.4.7.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for nexus-framework 0.4.7
File Interpreter ABI Platform Actions
nexus_framework-0.4.7-py3-none-any.whl Python 3 none any Details for nexus_framework-0.4.7-py3-none-any.whl

Total release size: 646.2 kB

Release files / nexus_framework-0.4.7.tar.gz

Download URL nexus_framework-0.4.7.tar.gz
Size 293.3 kB
Tags Source
SHA-256 checksum
How to use checksums
a510b181106ad8d08777adef614c5355b2e19515ff181b24febd2a6cab699e60
BLAKE2b-256 checksum
How to use checksums
4d38774ab87cb4202779c8d9387dd376ae44a25535a9fd717785b8c6ca76c267
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.9

Release files / nexus_framework-0.4.7-py3-none-any.whl

Download URL nexus_framework-0.4.7-py3-none-any.whl
Size 352.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cfcf11938daf13971c08d59c3c1da7df82383e2679ecdb3525daa4d5fbe521bc
BLAKE2b-256 checksum
How to use checksums
dac841ca3697101128b7a2f65a90cbeff8342cddb20f58267115f2a0c9952fa4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.9

Security for nexus-framework 0.4.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page