fastapi-utilities


Namefastapi-utilities JSON
Version 0.3.0 PyPI version JSON
download
home_pageNone
SummaryReusable utilities for FastAPI
upload_time2024-10-27 19:06:41
maintainerNone
docs_urlNone
authorPriyanshu Panwar
requires_python<4.0,>=3.7
licenseMIT
keywords fastapi utilities utils
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <p align="center">
    <em>🎨⚡️🔥 Reusable Utilities for FastAPI</em>
</p>
<p align="center">
<img src="https://img.shields.io/github/last-commit/priyanshu-panwar/fastapi-utilities.svg" />
<a href="https://github.com/priyanshu-panwar/fastapi-utilities/actions/workflows/build.yaml" > 
 <img src="https://github.com/priyanshu-panwar/fastapi-utilities/actions/workflows/build.yaml/badge.svg"/> 
 </a>
<a href="https://codecov.io/gh/priyanshu-panwar/fastapi-utilities" > 
 <img src="https://codecov.io/gh/priyanshu-panwar/fastapi-utilities/graph/badge.svg?token=8ACG93WM6I"/> 
 </a>
<br />
<a href="https://pypi.org/project/fastapi-utilities" target="_blank">
<img src="https://badge.fury.io/py/fastapi-utilities.svg" alt="Package version">
</a>
<img alt="PyPI - Python Version" src="https://img.shields.io/pypi/pyversions/fastapi-utilities">
<img alt="PyPI - Python Version" src="https://img.shields.io/github/license/priyanshu-panwar/fastapi-utilities.svg">
<br />
<a href="https://pepy.tech/project/fastapi-utilities" > 
 <img src="https://static.pepy.tech/badge/fastapi-utilities"/> 
 </a>
<a href="https://pepy.tech/project/fastapi-utilities" > 
 <img src="https://static.pepy.tech/badge/fastapi-utilities/month"/> 
 </a>
<a href="https://pepy.tech/project/fastapi-utilities" > 
 <img src="https://static.pepy.tech/badge/fastapi-utilities/week"/> 
 </a>
</p>

---

**Source Code**: <a href="https://github.com/priyanshu-panwar/fastapi-utilities" target="_blank">https://github.com/priyanshu-panwar/fastapi-utilities</a>  
**Youtube Link**: [Click Here](https://youtu.be/ZIggeTU8JhQ?si=SO1B0Is0RdXDkbCa)

_Inspired From_: <a href="https://github.com/dmontagu/fastapi-utils" target="_blank">dmontagu/fastapi-utils</a>

---

## [✨Update✨] How to use with Latest FastAPI version

With the latest FastAPI version, `on_event` lifespan functions are depreceated. Here is the official [doc](https://fastapi.tiangolo.com/advanced/events/#async-context-manager).
We need to make use of `asynccontextmanager` with the latest fastapi.

Here is an example how to use lifespan (Repeated Tasks) functions with latest fastapi:

```
from fastapi import FastAPI
from contextlib import asynccontextmanager
from fastapi_utilities import repeat_every, repeat_at

@asynccontextmanager
async def lifespan(app: FastAPI):
    # --- startup ---
    await test()
    test2()
    yield
    # --- shutdown ---

app = FastAPI(lifespan=lifespan)

# Repeat Every Example
@repeat_every(seconds=2)
async def test():
    print("test")

# Repeat At Example
@repeat_at(cron="* * * * *")
def test2():
    print("test2")
```

Only difference is to call our tasks from lifespan function instead of using `on_event` function.

---

## [🔥New🔥] TTL LRU CACHE

We have introduced `ttl_lru_cache` now in our library.

### How to use

```
from fastapi_utilities import ttl_lru_cache

@ttl_lru_cache(ttl=2, max_size=128)
def sum(a: int, b: int) -> int:
    return a + b

sum(1, 3)
sum(1, 3)
```

---

## [🔥New🔥] FastAPI CLI Tool

With our CLI Tool you can get a skeleton project built to get you started with the code.

### How to use

- Using `poetry`: `poetry run cli init`
- Using `pip`: `python3 -m cli init`

---

## Features

This package includes a number of utilities to help reduce boilerplate and reuse common functionality across projects:

- **🕒Repeated Tasks**: Easily trigger periodic tasks on server startup using **repeat_every**.

```

from fastapi_utilities import repeat_every

@router.on_event('startup')
@repeat_every(seconds=3)
async def print_hello():

    print("hello")
```

- **👷Cron Jobs**: Easily trigger cron jobs on server startup using **repeat_at** by providing a cron expression.

```

from fastapi_utilities import repeat_at

@router.on_event("startup")
@repeat_at(cron="*/2 * * * *") #every 2nd minute
async def hey():
    print("hey")

```

- **🕒Timer Middleware**: Add a middleware to the FastAPI app that logs the time taken to process a request. Optionally, also logs the average response time.The average response time is reset after every (reset_after)100,000 requests.

```

import asyncio
from fastapi import FastAPI, Request
from fastapi_utilities import add_timer_middleware

app = FastAPI()
add_timer_middleware(app, show_avg=True)


@app.get("/")
def read_root():
    return {"message": "Hello, World!"}

```

Response Logs:

```
INFO:     (fastapi-utilities) "GET - /" :: Time Taken :: 0.97 ms
INFO:     :: Average Response Time :: 0.97 ms
```

- **Cached Sessions**: Now use cached sessions along with context manager instead of `get_db`.

```
from fastapi import FastAPI
from .db import Base, engine
from fastapi_utilities import FastAPISessionMaker, repeat_every
from .models import User
import random

app = FastAPI()
Base.metadata.create_all(bind=engine)

session_maker = FastAPISessionMaker("sqlite:///db.sqlite3")


@app.on_event("startup")
@repeat_every(seconds=5, raise_exceptions=True)
async def startup():
    print("Starting up...")
    with session_maker.context_session() as session:
        x = User(id=random.randint(0, 10000))
        session.add(x)
    print("Startup complete!")

```

---

## Requirements

This package is intended for use with any recent version of FastAPI and Python 3.7+.

## Installation

```bash
pip install fastapi-utilities
```

## License

This project is licensed under the terms of the MIT license.


            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "fastapi-utilities",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.7",
    "maintainer_email": null,
    "keywords": "fastapi, utilities, utils",
    "author": "Priyanshu Panwar",
    "author_email": "priyanshu009ch@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/f3/a3/f8d0e3c24b1eb1f0283009ad5341881bcd429b3477484b041dff3c6b4e26/fastapi_utilities-0.3.0.tar.gz",
    "platform": null,
    "description": "<p align=\"center\">\n    <em>\ud83c\udfa8\u26a1\ufe0f\ud83d\udd25 Reusable Utilities for FastAPI</em>\n</p>\n<p align=\"center\">\n<img src=\"https://img.shields.io/github/last-commit/priyanshu-panwar/fastapi-utilities.svg\" />\n<a href=\"https://github.com/priyanshu-panwar/fastapi-utilities/actions/workflows/build.yaml\" > \n <img src=\"https://github.com/priyanshu-panwar/fastapi-utilities/actions/workflows/build.yaml/badge.svg\"/> \n </a>\n<a href=\"https://codecov.io/gh/priyanshu-panwar/fastapi-utilities\" > \n <img src=\"https://codecov.io/gh/priyanshu-panwar/fastapi-utilities/graph/badge.svg?token=8ACG93WM6I\"/> \n </a>\n<br />\n<a href=\"https://pypi.org/project/fastapi-utilities\" target=\"_blank\">\n<img src=\"https://badge.fury.io/py/fastapi-utilities.svg\" alt=\"Package version\">\n</a>\n<img alt=\"PyPI - Python Version\" src=\"https://img.shields.io/pypi/pyversions/fastapi-utilities\">\n<img alt=\"PyPI - Python Version\" src=\"https://img.shields.io/github/license/priyanshu-panwar/fastapi-utilities.svg\">\n<br />\n<a href=\"https://pepy.tech/project/fastapi-utilities\" > \n <img src=\"https://static.pepy.tech/badge/fastapi-utilities\"/> \n </a>\n<a href=\"https://pepy.tech/project/fastapi-utilities\" > \n <img src=\"https://static.pepy.tech/badge/fastapi-utilities/month\"/> \n </a>\n<a href=\"https://pepy.tech/project/fastapi-utilities\" > \n <img src=\"https://static.pepy.tech/badge/fastapi-utilities/week\"/> \n </a>\n</p>\n\n---\n\n**Source Code**: <a href=\"https://github.com/priyanshu-panwar/fastapi-utilities\" target=\"_blank\">https://github.com/priyanshu-panwar/fastapi-utilities</a>  \n**Youtube Link**: [Click Here](https://youtu.be/ZIggeTU8JhQ?si=SO1B0Is0RdXDkbCa)\n\n_Inspired From_: <a href=\"https://github.com/dmontagu/fastapi-utils\" target=\"_blank\">dmontagu/fastapi-utils</a>\n\n---\n\n## [\u2728Update\u2728] How to use with Latest FastAPI version\n\nWith the latest FastAPI version, `on_event` lifespan functions are depreceated. Here is the official [doc](https://fastapi.tiangolo.com/advanced/events/#async-context-manager).\nWe need to make use of `asynccontextmanager` with the latest fastapi.\n\nHere is an example how to use lifespan (Repeated Tasks) functions with latest fastapi:\n\n```\nfrom fastapi import FastAPI\nfrom contextlib import asynccontextmanager\nfrom fastapi_utilities import repeat_every, repeat_at\n\n@asynccontextmanager\nasync def lifespan(app: FastAPI):\n    # --- startup ---\n    await test()\n    test2()\n    yield\n    # --- shutdown ---\n\napp = FastAPI(lifespan=lifespan)\n\n# Repeat Every Example\n@repeat_every(seconds=2)\nasync def test():\n    print(\"test\")\n\n# Repeat At Example\n@repeat_at(cron=\"* * * * *\")\ndef test2():\n    print(\"test2\")\n```\n\nOnly difference is to call our tasks from lifespan function instead of using `on_event` function.\n\n---\n\n## [\ud83d\udd25New\ud83d\udd25] TTL LRU CACHE\n\nWe have introduced `ttl_lru_cache` now in our library.\n\n### How to use\n\n```\nfrom fastapi_utilities import ttl_lru_cache\n\n@ttl_lru_cache(ttl=2, max_size=128)\ndef sum(a: int, b: int) -> int:\n    return a + b\n\nsum(1, 3)\nsum(1, 3)\n```\n\n---\n\n## [\ud83d\udd25New\ud83d\udd25] FastAPI CLI Tool\n\nWith our CLI Tool you can get a skeleton project built to get you started with the code.\n\n### How to use\n\n- Using `poetry`: `poetry run cli init`\n- Using `pip`: `python3 -m cli init`\n\n---\n\n## Features\n\nThis package includes a number of utilities to help reduce boilerplate and reuse common functionality across projects:\n\n- **\ud83d\udd52Repeated Tasks**: Easily trigger periodic tasks on server startup using **repeat_every**.\n\n```\n\nfrom fastapi_utilities import repeat_every\n\n@router.on_event('startup')\n@repeat_every(seconds=3)\nasync def print_hello():\n\n    print(\"hello\")\n```\n\n- **\ud83d\udc77Cron Jobs**: Easily trigger cron jobs on server startup using **repeat_at** by providing a cron expression.\n\n```\n\nfrom fastapi_utilities import repeat_at\n\n@router.on_event(\"startup\")\n@repeat_at(cron=\"*/2 * * * *\") #every 2nd minute\nasync def hey():\n    print(\"hey\")\n\n```\n\n- **\ud83d\udd52Timer Middleware**: Add a middleware to the FastAPI app that logs the time taken to process a request. Optionally, also logs the average response time.The average response time is reset after every (reset_after)100,000 requests.\n\n```\n\nimport asyncio\nfrom fastapi import FastAPI, Request\nfrom fastapi_utilities import add_timer_middleware\n\napp = FastAPI()\nadd_timer_middleware(app, show_avg=True)\n\n\n@app.get(\"/\")\ndef read_root():\n    return {\"message\": \"Hello, World!\"}\n\n```\n\nResponse Logs:\n\n```\nINFO:     (fastapi-utilities) \"GET - /\" :: Time Taken :: 0.97 ms\nINFO:     :: Average Response Time :: 0.97 ms\n```\n\n- **Cached Sessions**: Now use cached sessions along with context manager instead of `get_db`.\n\n```\nfrom fastapi import FastAPI\nfrom .db import Base, engine\nfrom fastapi_utilities import FastAPISessionMaker, repeat_every\nfrom .models import User\nimport random\n\napp = FastAPI()\nBase.metadata.create_all(bind=engine)\n\nsession_maker = FastAPISessionMaker(\"sqlite:///db.sqlite3\")\n\n\n@app.on_event(\"startup\")\n@repeat_every(seconds=5, raise_exceptions=True)\nasync def startup():\n    print(\"Starting up...\")\n    with session_maker.context_session() as session:\n        x = User(id=random.randint(0, 10000))\n        session.add(x)\n    print(\"Startup complete!\")\n\n```\n\n---\n\n## Requirements\n\nThis package is intended for use with any recent version of FastAPI and Python 3.7+.\n\n## Installation\n\n```bash\npip install fastapi-utilities\n```\n\n## License\n\nThis project is licensed under the terms of the MIT license.\n\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Reusable utilities for FastAPI",
    "version": "0.3.0",
    "project_urls": null,
    "split_keywords": [
        "fastapi",
        " utilities",
        " utils"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "102285c032dd5636dc3396e1cc77ddbd9aa1e947bc654315a8c4e1f97b8e6c02",
                "md5": "c904ff7889c459f3d25777423eb6dcad",
                "sha256": "78dbcd54995900002370ee87e6b5de05ff69bce93e19d6a236f7810e5dc9c2f7"
            },
            "downloads": -1,
            "filename": "fastapi_utilities-0.3.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c904ff7889c459f3d25777423eb6dcad",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.7",
            "size": 15577,
            "upload_time": "2024-10-27T19:06:39",
            "upload_time_iso_8601": "2024-10-27T19:06:39.442995Z",
            "url": "https://files.pythonhosted.org/packages/10/22/85c032dd5636dc3396e1cc77ddbd9aa1e947bc654315a8c4e1f97b8e6c02/fastapi_utilities-0.3.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "f3a3f8d0e3c24b1eb1f0283009ad5341881bcd429b3477484b041dff3c6b4e26",
                "md5": "30c1fbaee2fce80f2b0f42ae2c6ffc7c",
                "sha256": "8b11061310b355eb9a9a65b93170611639fd8a6960658e7a1aff881fd7e6a157"
            },
            "downloads": -1,
            "filename": "fastapi_utilities-0.3.0.tar.gz",
            "has_sig": false,
            "md5_digest": "30c1fbaee2fce80f2b0f42ae2c6ffc7c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.7",
            "size": 10377,
            "upload_time": "2024-10-27T19:06:41",
            "upload_time_iso_8601": "2024-10-27T19:06:41.036233Z",
            "url": "https://files.pythonhosted.org/packages/f3/a3/f8d0e3c24b1eb1f0283009ad5341881bcd429b3477484b041dff3c6b4e26/fastapi_utilities-0.3.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-27 19:06:41",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "fastapi-utilities"
}
        
Elapsed time: 0.40739s