Skip to main content

Asynchronous FastAPI toolkit with service bootstrap, resource orchestration, and observability utilities

Project description

Linglong Web

Python Version License Code Style

Linglong Web is a FastAPI toolkit for microservice scenarios, focusing on "simple startup, flexible extension, and complete observability".

中文文档:see README.zh-CN.md

Links

Why this library

When building microservices with FastAPI, you often need:

  • Service lifecycle management - startup, shutdown, health checks, graceful termination
  • Resource orchestration - database connections, cache, message queues, schedulers
  • Observability - request-id propagation, structured logging, rate limiting
  • Extensibility - plugin hooks for service registration, remote config, etc.

Linglong Web provides all these out of the box as modular components.

Features

  • AppServer lifecycle - Built-in middleware, error handling, health checks, and signal handling
  • Extension hooks - on_config_ready, on_app_created, on_startup, on_shutdown for custom logic injection
  • Thread-safe config - LinglongConfig with hot reload support
  • Resource management - Unified initialization for PostgreSQL, Redis, MongoDB, RabbitMQ, Celery
  • HTTP client - aiohttp wrapper with request-id propagation and unified error handling
  • Decorators - Redis cache, rate limit, and distributed lock decorators
  • Scheduler - aioclock integration for periodic tasks
  • Bilingual comments - Chinese and English comments throughout the codebase

Installation

# Core: FastAPI bootstrapper + HTTP client + scheduler + Redis-backed decorators
pip install linglong-web

# Add resource backends on demand
pip install "linglong-web[postgres]"   # PostgreSQL (asyncpg + SQLAlchemy)
pip install "linglong-web[mongo]"      # MongoDB (PyMongo async)
pip install "linglong-web[rabbitmq]"   # RabbitMQ (aio-pika)
pip install "linglong-web[celery]"     # Celery
pip install "linglong-web[all]"        # everything

import linglong_web always works with just the core install; a backend you haven't installed only raises a clear error if you actually initialize it.

Quick Start

import asyncio

from linglong_web import LinglongConfigBase, init_config
from linglong_web import build_success_response
from linglong_web import BaseRoute, ServerRouter
from linglong_web import LinglongAppServer


class DevConfig(LinglongConfigBase):
    """Development configuration"""
    DEBUG = True
    SERVICE_NAME = "demo-service"


router = ServerRouter()
router.initialize([
    BaseRoute(
        path="/ping",
        method="GET",
        handler=lambda: build_success_response({"pong": True}),
    )
])

init_config({"dev": DevConfig}, mode_name="dev")


async def main():
    app_server = LinglongAppServer()
    await app_server.initialize(
        service_name="demo-service",
        router=router.get_router(),
        config_dict={"dev": DevConfig},
    )
    await app_server.start(host="0.0.0.0", port=8080)


if __name__ == "__main__":
    asyncio.run(main())

Module Overview

Module Description
server FastAPI bootstrapper with middlewares & extension hooks
server_extensions Lifecycle extension protocol for custom capabilities
config Thread-safe config proxy with hot reload
resource Unified resource bootstrapper (DB, Cache, MQ, Scheduler)
http aiohttp client with request-id injection
cacher Redis cache decorator
limiter Rate limit decorator
cluster_lock Distributed lock decorator
scheduler aioclock helpers for periodic tasks
utils Context, logging, signal handling, time utilities

Extension Example

from linglong_web.server_extensions import BaseServerExtension


class RegistryExtension(BaseServerExtension):
    """Example: custom service registration logic"""

    def __init__(self, client):
        self._client = client

    async def on_startup(self, server):
        payload = {"service": server.service_name, "instance": server.instance_id}
        await self._client.register(payload)
        server.register_shutdown_callback(lambda: self._client.deregister(payload))


extensions = [RegistryExtension(client)]
await app_server.initialize(
    service_name="demo",
    router=router.get_router(),
    config_dict={"dev": DevConfig},
    extensions=extensions,
)

Linglong no longer bundles service registration or remote config capabilities. Implement them in your business repository using extension hooks.

Testing & Coverage

# Run tests with coverage
pytest tests/ -v --cov=linglong_web --cov-report=term-missing

# Or with PYTHONPATH
PYTHONPATH=. pytest tests/ -v --cov=linglong_web --cov-report=term-missing
  • All new modules should maintain 80%+ test coverage.
  • Use pytest-asyncio and pytest-mock for fine-grained mocking of resources, rate limiters, and signal handlers.

Project Layout

linglong_web/
├── linglong_web/
│   ├── core/               # Core modules
│   │   ├── server.py       # FastAPI bootstrapper
│   │   ├── config.py       # Config proxy
│   │   ├── resource.py     # Resource manager
│   │   ├── http.py         # HTTP client
│   │   ├── cacher.py       # Cache decorator
│   │   ├── limiter.py      # Rate limit decorator
│   │   └── ...
│   └── utils/              # Utilities
├── tests/                  # Test suite
└── docs/                   # Documentation

Versioning

The package version is sourced from linglong_web/__version__.py.

License

MIT License. See LICENSE.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

linglong_web-0.0.2.tar.gz (78.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

linglong_web-0.0.2-py3-none-any.whl (64.4 kB view details)

Uploaded Python 3

File details

Details for the file linglong_web-0.0.2.tar.gz.

File metadata

  • Download URL: linglong_web-0.0.2.tar.gz
  • Upload date:
  • Size: 78.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for linglong_web-0.0.2.tar.gz
Algorithm Hash digest
SHA256 9593022b37a2bd850817b97072860c159e9436d5a52e966ceb05d8e195edd4f4
MD5 4fe5292762f2dbdaf3ee10e14fb9b43e
BLAKE2b-256 4d43471beae54c2cf3ba41199fb1d8296be26306059217042504760ec97a89af

See more details on using hashes here.

Provenance

The following attestation bundles were made for linglong_web-0.0.2.tar.gz:

Publisher: publish.yml on 10000ms/linglong_web

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file linglong_web-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: linglong_web-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 64.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for linglong_web-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 ea9e9dcc8c1f3a86cf57e9d896616feaab14061bea59158e98ac276b431319a4
MD5 744b3a9281fd515ae9f0204843dbe0f3
BLAKE2b-256 fd43eb06aa874c009c17eb229b5e46b881b9bf4761c5f5acb9a023bec918e901

See more details on using hashes here.

Provenance

The following attestation bundles were made for linglong_web-0.0.2-py3-none-any.whl:

Publisher: publish.yml on 10000ms/linglong_web

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page