Skip to main content

Common utilities for FastAPI applications

Project description

FastAPI Toolbox

中文文档 | English

A Python library that provides common utilities and features for FastAPI development, including static file cache control and advanced logging system.

Installation

uv add fastapi-toolbox
pip install fastapi-toolbox

Features

Running Server

fastapi-toolbox provides an advanced logging system based on loguru, supporting log configuration in multi-process environments.

Basic Usage

from fastapi import FastAPI
from fastapi_toolbox import logger, run_server
import uvicorn
import logging

app = FastAPI()

@app.get("/")
async def read_root():
    logger.info("Hello World accessed")
    return {"Hello": "World"}

if __name__ == "__main__":

    def filter_sqlalchemy(record):
        if record.name.startswith("sqlalchemy"):
            if record.levelno < logging.ERROR:
                return True

    run_server(
        "main:app",
        host="127.0.0.1",
        port=8000,
        workers=1,
        log_file="logs/app.log", # Log rotation
        filter_callbacks=[filter_sqlalchemy]
    )

Environment Variable Configuration

  • LOG_LEVEL: Set log level (DEBUG, INFO, WARNING, ERROR), defaults to INFO
  • JSON_LOGS: Set to "1" to enable JSON format logs, defaults to standard format

Key Features

  • Multi-process Support: UvicornConfig ensures logs work properly in multi-process environments
  • Auto Rotation: Supports log rotation by file size and time
  • Unified Interception: Automatically intercepts standard library logging and forwards to loguru
  • Flexible Configuration: Supports environment variables and code configuration

StaticFilesCache

StaticFilesCache is an enhanced version of FastAPI StaticFiles, providing configurable cache control for static files.

Basic Usage

from fastapi import FastAPI
from fastapi_toolbox import StaticFilesCache
import os

app = FastAPI()

# Example 1: Using default cache policy (cache disabled)
front_folder = os.path.join(os.path.dirname(__file__), "frontend/dist")
app.mount("/", StaticFilesCache(directory=front_folder), name="static")

# Example 2: Using custom cache policy
app.mount("/static", StaticFilesCache(
    directory="static_files",
    cachecontrol="max-age=3600"  # Cache for 1 hour
), name="static")

Key Features

  • Auto Cache Control: Automatically adds Cache-Control response headers for .html and .txt files
  • Configurable Policy: Customize cache behavior via cachecontrol parameter
  • Full Compatibility: Inherits from FastAPI StaticFiles, retaining all original functionality

Parameters

Parameter Description Default
directory Static files directory path Required
cachecontrol Cache-Control header value "no-cache, no-store, must-revalidate"
Other parameters Same as standard StaticFiles -

Common Cache Strategies

# Disable cache (suitable for development)
cachecontrol="no-cache, no-store, must-revalidate"

# Short-term cache (suitable for frequently updated resources)
cachecontrol="max-age=3600"  # 1 hour

# Long-term cache (suitable for rarely changed resources)
cachecontrol="public, max-age=86400"  # 1 day

# Private cache, must revalidate
cachecontrol="private, must-revalidate"

Practical Use Cases

Suitable for scenarios where you need to serve static files for frontend SPA applications:

# Access http://127.0.0.1:8000/index.html to view the frontend page
front_folder = os.path.join(os.path.dirname(__file__), "frontend/dist")
app.mount("/", StaticFilesCache(directory=front_folder), name="static")

With this configuration, HTML files will not be cached by the browser, ensuring users always get the latest version of the frontend application.

NextJSRouteMiddleware

NextJSRouteMiddleware is a middleware for handling Next.js static export routes. When a request returns 404, it attempts to find the corresponding .html file.

Basic Usage

from fastapi import FastAPI
from fastapi_toolbox import NextJSRouteMiddleware

app = FastAPI()

# Add middleware
app.add_middleware(
    NextJSRouteMiddleware,
    static_dir="frontend/dist",
    skip_prefixes=["/api", "/static", "/docs", "/openapi.json", "/redoc"],
)

Parameters

Parameter Description Default
static_dir Static files directory path Required
skip_prefixes List of path prefixes to skip processing []
index_file Default filename for root path (without extension) "index"

How It Works

  1. Requests matching skip_prefixes are passed through directly
  2. Other requests are processed normally
  3. If 404 is returned and path doesn't start with /_next, it looks for the corresponding .html file
  4. For example: /about → looks for frontend/dist/about.html
  5. Root path / → looks for frontend/dist/index.html

Practical Example

from fastapi import FastAPI
from fastapi_toolbox import NextJSRouteMiddleware, StaticFilesCache
import os

app = FastAPI()

front_folder = os.path.join(os.path.dirname(__file__), "frontend/dist")

# Add Next.js route middleware
app.add_middleware(
    NextJSRouteMiddleware,
    static_dir=front_folder,
    skip_prefixes=[
        "/api",
        "/static",
        "/_next",
        "/docs",
        "/openapi.json",
        "/redoc",
        "/favicon.ico",
    ],
)

# Mount static files
app.mount("/", StaticFilesCache(directory=front_folder), name="static")

Build

uv build

Publish

uv publish

Enter __token__ as username and then enter your PyPI token

License

MIT

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

fastapi_toolbox-0.6.7.tar.gz (19.2 kB view details)

Uploaded Source

Built Distribution

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

fastapi_toolbox-0.6.7-py3-none-any.whl (23.6 kB view details)

Uploaded Python 3

File details

Details for the file fastapi_toolbox-0.6.7.tar.gz.

File metadata

  • Download URL: fastapi_toolbox-0.6.7.tar.gz
  • Upload date:
  • Size: 19.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for fastapi_toolbox-0.6.7.tar.gz
Algorithm Hash digest
SHA256 10dc2abeed1c86386b2066a1787c1ba0fc732c8af9e2895ef2d4dcbbbf1eefc5
MD5 6c575a46c4c7dcb8d14ed49457b80862
BLAKE2b-256 2fe2237e5ea7a90048a5981ea7fdff1b114392d81e61f2fd0a366aa5bd2427f0

See more details on using hashes here.

File details

Details for the file fastapi_toolbox-0.6.7-py3-none-any.whl.

File metadata

  • Download URL: fastapi_toolbox-0.6.7-py3-none-any.whl
  • Upload date:
  • Size: 23.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.9.18 {"installer":{"name":"uv","version":"0.9.18","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

File hashes

Hashes for fastapi_toolbox-0.6.7-py3-none-any.whl
Algorithm Hash digest
SHA256 b4165f25ac96b30769f029c9ef5525dc4c413e9240f4d623c09289f7a4814a1b
MD5 c6fad41abcdb1f635d88e2ca0653a82a
BLAKE2b-256 3ce8c8a2881988d2af728bd13c3bb57cb3311a162daac25a7a0a78ec25062ea6

See more details on using hashes here.

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