SkillAgentSearch skills...

Blazeio

Blazeio is an ultra-fast asynchronous web framework crafted for high-performance backend applications. Built on Python's asyncio, it delivers non-blocking operations, minimal overhead, and lightning-quick request handling.

Install / Use

/learn @anonyxbiz/Blazeio
About this skill

Quality Score

0/100

Category

Design

Supported Platforms

Universal

README

Overview

Blazeio is a cutting-edge asynchronous web server and client framework designed for building high-performance backend applications with minimal overhead.

Built on Python's asyncio event loop, Blazeio provides:

  • Zero-copy streaming
  • Protocol-agnostic request handling
  • Automatic backpressure management
  • Microsecond-level reactivity
  • Connection-aware processing

Blazeio operates at the transport layer while maintaining a simple, developer-friendly API.

Key Features

  • 🚀 Event-optimized I/O: Direct socket control with smart backpressure
  • Instant disconnect detection: No zombie connections
  • 🔄 Bidirectional streaming: HTTP/1.1, SSE, and custom protocols
  • 🧠 Memory-safe architecture: No buffer overflows
  • ⏱️ Precise flow control: Async sleeps instead of spinlocks
  • 🔗 Unified client/server API: Same code for both sides

Core API: Request Object

BlazeioServerProtocol (Request Object)

The foundation of Blazeio's performance comes from its optimized request handling:

class BlazeioServerProtocol(BufferedProtocol, BlazeioPayloadUtils, ExtraToolset):
    __slots__ = (
        'transport', 'method', 'path', 'headers',
        'content_length', 'current_length', 'transfer_encoding'
        # ... and other internal state
    )

Essential Methods

Connection Management

def connection_made(self, transport):
    """Called when new client connects"""
    self.transport = transport

def connection_lost(self, exc):
    """Called when client disconnects"""
    self.__is_alive__ = False

def abort_connection(self):
    """Called when the connection is half-opened"""

Flow Control

async def buffer_overflow_manager(self):
    """Sleeps at 0% CPU when kernel buffers are full"""
    if self.__is_buffer_over_high_watermark__:
        await self.__overflow_evt__.wait()
        self.__overflow_evt__.clear()

async def writer(self, data: bytes):
    """Safe write with backpressure and disconnect checks"""
    await self.buffer_overflow_manager()
    if not self.transport.is_closing():
        self.transport.write(data)

Streaming

async def __aiter__(self):
    """Generator for incoming data chunks"""
    while True:
        await self.ensure_reading()
        while self.__stream__:
            yield self.__stream__.popleft()

Advanced Features

Chunked Encoding

async def write_chunked(self, data):
    """HTTP chunked transfer encoding"""
    await self.writer(b"%X\r\n%s\r\n" % (len(data), data))

async def handle_chunked(self):
    """Parse incoming chunked data"""
    async for chunk in self:
        yield chunk  # Auto-decodes chunked encoding

Compression

async def br(self, data: bytes):
    """Brotli compression"""
    return await to_thread(brotlicffi_compress, data)

async def gzip(self, data: bytes):
    """Gzip compression"""
    encoder = compressobj(wbits=31)
    return encoder.compress(data) + encoder.flush()

Modules

Blazeio consists of several modules that each serve a specific purpose. Below is a breakdown of the main modules included:

Core Module

  • App: The core app class that handles the event loop, server setup, and route management.
    • __init__(): Initializes the application.
    • add_route(): Adds routes dynamically.
    • handle_client(): Handles incoming requests and routes them to the appropriate handler.
    • runner(): Starts the server, listens for connections, and handles requests.
    • exit(): Gracefully shuts down the server.

Middleware

Blazeio includes various middlewares that provide hooks into the request/response lifecycle:

  • before_middleware: Executes before the target route is processed, ideal for logging or preparation tasks.
  • handle_all_middleware: Executes when no specific route is matched, instead of returning a 404 error.
  • after_middleware: Executes after the target route has been processed, for cleanup tasks or logging.

Request Module

The Request module provides utilities to work with incoming HTTP requests:

  • get_json: Parses JSON data from the request.
  • params: Retrieves URL parameters from the request.
  • pull: Streams the incoming data in chunks for the parsed protocol.
  • aiter: Streams the raw incoming data in chunks without protocol deserialization.

Streaming

  • Deliver: Manages data delivery and ensures that responses are properly handled.
  • Abort: An exception used to quickly abort a request.

Static File Handling

  • Simpleserve: Serves files directly from the server. This module is ideal for applications that require fast delivery of static content, such as websites serving assets like HTML, CSS, and JavaScript files, especially when theyre small files that are frequently accessed.

Middleware Usage

Blazeio’s middleware system allows you to hook into various stages of request processing.

Example of before_middleware

This middleware runs before the actual route handler is executed:

@web.add_route
async def before_middleware(request):
    # Perform some task before the route is executed
    print("Before route executed.")

Example of after_middleware

This middleware runs after the route handler finishes:

@web.add_route
async def after_middleware(request):
    # Perform some task after the route is executed
    print("After route executed.")

Example of handle_all_middleware

This middleware runs when no specific route is matched, avoiding a default 404 response:

@web.add_route
async def handle_all_middleware(request):
    raise Blazeio.Abort("Route not found, but handled.", 404)

Tools & Request Utilities

Blazeio includes several useful tools to make handling requests easier:

Request Tools

  • .get_json: Retrieve JSON data from the request body:

    json_data = await request.get_json()
    
  • .form_data: Retrieve form data, including file upload form data:

    form_data = await request.form_data(r)
    
  • .pull: Stream file uploads in chunks:

    async for chunk in request.pull():
        ...
        # Process file chunk
    

Blazeio Quick Start Guide

Requirements

Python 3.7+, psutil, aiofile, brotlicffi, xmltodict.

pip install blazeio

Example Application

This example demonstrates both Object-Oriented Programming (OOP) and Functional Programming (FP) approaches to define routes and middleware.

Full Example Code

import Blazeio as io

web = io.App("0.0.0.0", 8000, with_keepalive = 1)

web.attach(io.StaticServer("/", io.path.join(io.getcwd(), "static"), 1024*100, "page", "index.html"))

# OOP IMPLEMENTATION
@web.attach
class Server:
    def __init__(app):
        ...

    async def before_middleware(app, r):
        r.store = {"json_data": await r.body_or_params()}

    # /
    async def _redirect(app, r):
        # Redirect users to the IP endpoint
        raise io.Abort("", 302, io.ddict(location = "/api/ip"))

    # handle undefined endpoints and serve static files
    async def handle_all_middleware(app, r):
        raise io.Abort("Not Found", 404)

    # /api/ip/
    async def _api_ip(app, r):
        data = {
            "ip": str(r.ip_host) + str(r.ip_port)
        }

        await io.Deliver.json(data)

# FP Implementation
@web.add_route
async def this_function_name_wont_be_used_as_the_route_if_overriden_in_the_route_param(r, route="/fp"):
    # Send a text response
    await io.Deliver.text("Hello from some functional endpoint")

if __name__ == "__main__":
    with web:
        web.runner()

Explanation

  1. Object-Oriented Programming (OOP) Approach:

    • Server class sets up the application defining routes from methods.
    • Custom middleware is added for request handling (before_middleware) and for handling undefined routes (handle_all_middleware).
  2. Functional Programming (FP) Approach:

    • The @web.add_route decorator is used to define functional endpoints. The this_function_name_wont_be_used_as_the_route_if_overriden_in_the_route_param function handles the /fp route.
  3. Middleware and Request Handling:

    • The before_middleware method ensures that incoming requests have the necessary JSON or form data parsed and stored in r.json_data.
    • The handle_all_middleware metho handles undefined routes.

Running the App

  1. Create a Python file (e.g., app.py) and paste the example code above.
  2. Run the app with:
python app.py
  1. Open your browser and visit http://localhost:8000 to view the app. You should see a static page, visit http://localhost:8000/redirect and it will redirect to /api/ip, which returns your IP.

Customizing Routes

  • To add more routes, simply create new methods starting with _ inside the Server class. The method name (with _ replaced by /) will be automatically mapped to the corresponding route.

Example:

async def _new_route(app, r):
    await io.Deliver.text("This is /new/route")

This will automatically add a new route at /new/route.

Why Blazeio?

  1. Zero-Copy Architecture

    • No unnecessary data copies between kernel and userspace
    • Memory views instead of byte duplication
  2. Microsecond-Level Reactivity

    • Small chunk sizes (default 4KB) enable rapid feedback
    • Immediate disconnect detection
  3. Self-Healing Design

    • Automatic cleanup of dead connections

Example Use Cases

Blazeio WebRTC-like Signaling Server Example

"""
Blazeio WebRTC-like Signaling Server Example

This example demonstrates a peer-to-peer signaling server that allows clients
to create "rooms" and establish direct connections through chunked transfer encoding.
It includes built-in performance testing capabilities.
"""

import Blazeio as io
import Blazeio.Other.class_parser as cl

Related Skills

View on GitHub
GitHub Stars13
CategoryDesign
Updated2d ago
Forks0

Languages

Python

Security Score

95/100

Audited on Apr 4, 2026

No findings