fastapi-toolbox


Namefastapi-toolbox JSON
Version 0.6.1 PyPI version JSON
download
home_pageNone
SummaryCommon utilities for FastAPI applications
upload_time2025-10-28 08:37:47
maintainerNone
docs_urlNone
authorNone
requires_python>=3.12
licenseMIT
keywords fastapi starlette utilities web
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # FastAPI Toolbox

这是一个Python库,提供FastAPI开发时的常用工具和功能,包括静态文件缓存控制和高级日志系统。

## 安装

```bash
uv add fastapi-toolbox
```

```bash
pip install fastapi-toolbox
```

## 功能特性

### 运行服务器

`fastapi-toolbox` 提供了基于 loguru 的高级日志系统,支持多进程环境下的日志配置。

#### 基本用法

```python
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访问")
    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", # 日志轮转
        filter_callbacks=[filter_sqlalchemy]
    )
```


#### 环境变量配置

- `LOG_LEVEL`: 设置日志级别(DEBUG, INFO, WARNING, ERROR),默认INFO
- `JSON_LOGS`: 设置为"1"启用JSON格式日志,默认为标准格式

#### 主要特性

- **多进程支持**:`UvicornConfig` 确保多进程环境下日志正常工作
- **自动轮转**:支持按文件大小和时间进行日志轮转
- **统一拦截**:自动拦截标准库logging并转发到loguru
- **灵活配置**:支持环境变量和代码配置

### StaticFilesCache

`StaticFilesCache` 是 FastAPI StaticFiles 的增强版本,为静态文件提供可配置的缓存控制功能。

#### 基本用法

```python
from fastapi import FastAPI
from fastapi_toolbox import StaticFilesCache
import os

app = FastAPI()

# 示例1:使用默认缓存策略(禁用缓存)
front_folder = os.path.join(os.path.dirname(__file__), "frontend/dist")
app.mount("/", StaticFilesCache(directory=front_folder), name="static")

# 示例2:使用自定义缓存策略
app.mount("/static", StaticFilesCache(
    directory="static_files",
    cachecontrol="max-age=3600"  # 缓存1小时
), name="static")
```

#### 主要特性

- **自动缓存控制**:自动为 `.html` 和 `.txt` 文件添加 Cache-Control 响应头
- **可配置策略**:通过 `cachecontrol` 参数自定义缓存行为
- **完全兼容**:继承自 FastAPI StaticFiles,保留所有原有功能

#### 参数说明

| 参数 | 说明 | 默认值 |
|------|------|--------|
| `directory` | 静态文件目录路径 | 必填 |
| `cachecontrol` | Cache-Control 头的值 | `"no-cache, no-store, must-revalidate"` |
| 其他参数 | 与标准 StaticFiles 相同 | - |

#### 常用缓存策略

```python
# 禁用缓存(适合开发环境)
cachecontrol="no-cache, no-store, must-revalidate"

# 短期缓存(适合经常更新的资源)
cachecontrol="max-age=3600"  # 1小时

# 长期缓存(适合不常变动的资源)
cachecontrol="public, max-age=86400"  # 1天

# 私有缓存,必须重新验证
cachecontrol="private, must-revalidate"
```

#### 实际应用场景

适用于需要为前端SPA应用提供静态文件服务的场景:

```python
# 访问 http://127.0.0.1:8000/index.html 即可访问前端页面
front_folder = os.path.join(os.path.dirname(__file__), "frontend/dist")
app.mount("/", StaticFilesCache(directory=front_folder), name="static")
```

这样配置后,HTML文件将不会被浏览器缓存,确保用户总是获取最新版本的前端应用。

## 构建

uv build

## 发布

uv publish

输入__token__作为用户名 然后输入pypi的token

## License

MIT
            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "fastapi-toolbox",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.12",
    "maintainer_email": null,
    "keywords": "fastapi, starlette, utilities, web",
    "author": null,
    "author_email": "wynemo <ggdabin@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/41/36/d301504c63fc1ca0319017a1f159f8aeb11ebf369a20b28c6174c7901f40/fastapi_toolbox-0.6.1.tar.gz",
    "platform": null,
    "description": "# FastAPI Toolbox\n\n\u8fd9\u662f\u4e00\u4e2aPython\u5e93\uff0c\u63d0\u4f9bFastAPI\u5f00\u53d1\u65f6\u7684\u5e38\u7528\u5de5\u5177\u548c\u529f\u80fd\uff0c\u5305\u62ec\u9759\u6001\u6587\u4ef6\u7f13\u5b58\u63a7\u5236\u548c\u9ad8\u7ea7\u65e5\u5fd7\u7cfb\u7edf\u3002\n\n## \u5b89\u88c5\n\n```bash\nuv add fastapi-toolbox\n```\n\n```bash\npip install fastapi-toolbox\n```\n\n## \u529f\u80fd\u7279\u6027\n\n### \u8fd0\u884c\u670d\u52a1\u5668\n\n`fastapi-toolbox` \u63d0\u4f9b\u4e86\u57fa\u4e8e loguru \u7684\u9ad8\u7ea7\u65e5\u5fd7\u7cfb\u7edf\uff0c\u652f\u6301\u591a\u8fdb\u7a0b\u73af\u5883\u4e0b\u7684\u65e5\u5fd7\u914d\u7f6e\u3002\n\n#### \u57fa\u672c\u7528\u6cd5\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_toolbox import logger, run_server\nimport uvicorn\nimport logging\n\napp = FastAPI()\n\n@app.get(\"/\")\nasync def read_root():\n    logger.info(\"Hello World\u8bbf\u95ee\")\n    return {\"Hello\": \"World\"}\n\nif __name__ == \"__main__\":\n\n    def filter_sqlalchemy(record):\n        if record.name.startswith(\"sqlalchemy\"):\n            if record.levelno < logging.ERROR:\n                return True\n\n    run_server(\n        \"main:app\",\n        host=\"127.0.0.1\",\n        port=8000,\n        workers=1,\n        log_file=\"logs/app.log\", # \u65e5\u5fd7\u8f6e\u8f6c\n        filter_callbacks=[filter_sqlalchemy]\n    )\n```\n\n\n#### \u73af\u5883\u53d8\u91cf\u914d\u7f6e\n\n- `LOG_LEVEL`: \u8bbe\u7f6e\u65e5\u5fd7\u7ea7\u522b\uff08DEBUG, INFO, WARNING, ERROR\uff09\uff0c\u9ed8\u8ba4INFO\n- `JSON_LOGS`: \u8bbe\u7f6e\u4e3a\"1\"\u542f\u7528JSON\u683c\u5f0f\u65e5\u5fd7\uff0c\u9ed8\u8ba4\u4e3a\u6807\u51c6\u683c\u5f0f\n\n#### \u4e3b\u8981\u7279\u6027\n\n- **\u591a\u8fdb\u7a0b\u652f\u6301**\uff1a`UvicornConfig` \u786e\u4fdd\u591a\u8fdb\u7a0b\u73af\u5883\u4e0b\u65e5\u5fd7\u6b63\u5e38\u5de5\u4f5c\n- **\u81ea\u52a8\u8f6e\u8f6c**\uff1a\u652f\u6301\u6309\u6587\u4ef6\u5927\u5c0f\u548c\u65f6\u95f4\u8fdb\u884c\u65e5\u5fd7\u8f6e\u8f6c\n- **\u7edf\u4e00\u62e6\u622a**\uff1a\u81ea\u52a8\u62e6\u622a\u6807\u51c6\u5e93logging\u5e76\u8f6c\u53d1\u5230loguru\n- **\u7075\u6d3b\u914d\u7f6e**\uff1a\u652f\u6301\u73af\u5883\u53d8\u91cf\u548c\u4ee3\u7801\u914d\u7f6e\n\n### StaticFilesCache\n\n`StaticFilesCache` \u662f FastAPI StaticFiles \u7684\u589e\u5f3a\u7248\u672c\uff0c\u4e3a\u9759\u6001\u6587\u4ef6\u63d0\u4f9b\u53ef\u914d\u7f6e\u7684\u7f13\u5b58\u63a7\u5236\u529f\u80fd\u3002\n\n#### \u57fa\u672c\u7528\u6cd5\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_toolbox import StaticFilesCache\nimport os\n\napp = FastAPI()\n\n# \u793a\u4f8b1\uff1a\u4f7f\u7528\u9ed8\u8ba4\u7f13\u5b58\u7b56\u7565\uff08\u7981\u7528\u7f13\u5b58\uff09\nfront_folder = os.path.join(os.path.dirname(__file__), \"frontend/dist\")\napp.mount(\"/\", StaticFilesCache(directory=front_folder), name=\"static\")\n\n# \u793a\u4f8b2\uff1a\u4f7f\u7528\u81ea\u5b9a\u4e49\u7f13\u5b58\u7b56\u7565\napp.mount(\"/static\", StaticFilesCache(\n    directory=\"static_files\",\n    cachecontrol=\"max-age=3600\"  # \u7f13\u5b581\u5c0f\u65f6\n), name=\"static\")\n```\n\n#### \u4e3b\u8981\u7279\u6027\n\n- **\u81ea\u52a8\u7f13\u5b58\u63a7\u5236**\uff1a\u81ea\u52a8\u4e3a `.html` \u548c `.txt` \u6587\u4ef6\u6dfb\u52a0 Cache-Control \u54cd\u5e94\u5934\n- **\u53ef\u914d\u7f6e\u7b56\u7565**\uff1a\u901a\u8fc7 `cachecontrol` \u53c2\u6570\u81ea\u5b9a\u4e49\u7f13\u5b58\u884c\u4e3a\n- **\u5b8c\u5168\u517c\u5bb9**\uff1a\u7ee7\u627f\u81ea FastAPI StaticFiles\uff0c\u4fdd\u7559\u6240\u6709\u539f\u6709\u529f\u80fd\n\n#### \u53c2\u6570\u8bf4\u660e\n\n| \u53c2\u6570 | \u8bf4\u660e | \u9ed8\u8ba4\u503c |\n|------|------|--------|\n| `directory` | \u9759\u6001\u6587\u4ef6\u76ee\u5f55\u8def\u5f84 | \u5fc5\u586b |\n| `cachecontrol` | Cache-Control \u5934\u7684\u503c | `\"no-cache, no-store, must-revalidate\"` |\n| \u5176\u4ed6\u53c2\u6570 | \u4e0e\u6807\u51c6 StaticFiles \u76f8\u540c | - |\n\n#### \u5e38\u7528\u7f13\u5b58\u7b56\u7565\n\n```python\n# \u7981\u7528\u7f13\u5b58\uff08\u9002\u5408\u5f00\u53d1\u73af\u5883\uff09\ncachecontrol=\"no-cache, no-store, must-revalidate\"\n\n# \u77ed\u671f\u7f13\u5b58\uff08\u9002\u5408\u7ecf\u5e38\u66f4\u65b0\u7684\u8d44\u6e90\uff09\ncachecontrol=\"max-age=3600\"  # 1\u5c0f\u65f6\n\n# \u957f\u671f\u7f13\u5b58\uff08\u9002\u5408\u4e0d\u5e38\u53d8\u52a8\u7684\u8d44\u6e90\uff09\ncachecontrol=\"public, max-age=86400\"  # 1\u5929\n\n# \u79c1\u6709\u7f13\u5b58\uff0c\u5fc5\u987b\u91cd\u65b0\u9a8c\u8bc1\ncachecontrol=\"private, must-revalidate\"\n```\n\n#### \u5b9e\u9645\u5e94\u7528\u573a\u666f\n\n\u9002\u7528\u4e8e\u9700\u8981\u4e3a\u524d\u7aefSPA\u5e94\u7528\u63d0\u4f9b\u9759\u6001\u6587\u4ef6\u670d\u52a1\u7684\u573a\u666f\uff1a\n\n```python\n# \u8bbf\u95ee http://127.0.0.1:8000/index.html \u5373\u53ef\u8bbf\u95ee\u524d\u7aef\u9875\u9762\nfront_folder = os.path.join(os.path.dirname(__file__), \"frontend/dist\")\napp.mount(\"/\", StaticFilesCache(directory=front_folder), name=\"static\")\n```\n\n\u8fd9\u6837\u914d\u7f6e\u540e\uff0cHTML\u6587\u4ef6\u5c06\u4e0d\u4f1a\u88ab\u6d4f\u89c8\u5668\u7f13\u5b58\uff0c\u786e\u4fdd\u7528\u6237\u603b\u662f\u83b7\u53d6\u6700\u65b0\u7248\u672c\u7684\u524d\u7aef\u5e94\u7528\u3002\n\n## \u6784\u5efa\n\nuv build\n\n## \u53d1\u5e03\n\nuv publish\n\n\u8f93\u5165__token__\u4f5c\u4e3a\u7528\u6237\u540d \u7136\u540e\u8f93\u5165pypi\u7684token\n\n## License\n\nMIT",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Common utilities for FastAPI applications",
    "version": "0.6.1",
    "project_urls": {
        "Homepage": "https://github.com/wynemo/fastapi-utils",
        "Issues": "https://github.com/wynemo/fastapi-utils/issues",
        "Repository": "https://github.com/wynemo/fastapi-utils.git"
    },
    "split_keywords": [
        "fastapi",
        " starlette",
        " utilities",
        " web"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "411d8dcaf4e43ccf719de1399e951527acd932c6f26714962f0587164dcaa8ee",
                "md5": "51a59ddd14cd8f20bc909dc9e4fdffe4",
                "sha256": "09c1be743838ad1591d922d16e5a324f763d345e7ac802ec6ec6493fd8491054"
            },
            "downloads": -1,
            "filename": "fastapi_toolbox-0.6.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "51a59ddd14cd8f20bc909dc9e4fdffe4",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.12",
            "size": 18598,
            "upload_time": "2025-10-28T08:37:46",
            "upload_time_iso_8601": "2025-10-28T08:37:46.692785Z",
            "url": "https://files.pythonhosted.org/packages/41/1d/8dcaf4e43ccf719de1399e951527acd932c6f26714962f0587164dcaa8ee/fastapi_toolbox-0.6.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "4136d301504c63fc1ca0319017a1f159f8aeb11ebf369a20b28c6174c7901f40",
                "md5": "7076f79dfc30fc1bcecc950d182e46dd",
                "sha256": "b46efdc83cd2b7046606a1ddc365768589197984c1b7b223ce46a545f106524c"
            },
            "downloads": -1,
            "filename": "fastapi_toolbox-0.6.1.tar.gz",
            "has_sig": false,
            "md5_digest": "7076f79dfc30fc1bcecc950d182e46dd",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.12",
            "size": 15679,
            "upload_time": "2025-10-28T08:37:47",
            "upload_time_iso_8601": "2025-10-28T08:37:47.906353Z",
            "url": "https://files.pythonhosted.org/packages/41/36/d301504c63fc1ca0319017a1f159f8aeb11ebf369a20b28c6174c7901f40/fastapi_toolbox-0.6.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-10-28 08:37:47",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "wynemo",
    "github_project": "fastapi-utils",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "fastapi-toolbox"
}
        
Elapsed time: 0.57373s