fast-depends


Namefast-depends JSON
Version 2.4.1 PyPI version JSON
download
home_page
SummaryFastDepends - extracted and cleared from HTTP domain logic FastAPI Dependency Injection System. Async and sync are both supported.
upload_time2024-02-25 14:27:17
maintainer
docs_urlNone
author
requires_python>=3.8
license
keywords dependency injection fastapi
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # FastDepends

<p align="center">
    <a href="https://github.com/Lancetnik/FastDepends/actions/workflows/tests.yml" target="_blank">
        <img src="https://github.com/Lancetnik/FastDepends/actions/workflows/tests.yml/badge.svg" alt="Tests coverage"/>
    </a>
    <a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/lancetnik/fastdepends" target="_blank">
        <img src="https://coverage-badge.samuelcolvin.workers.dev/lancetnik/fastdepends.svg" alt="Coverage">
    </a>
    <a href="https://pypi.org/project/fast-depends" target="_blank">
        <img src="https://img.shields.io/pypi/v/fast-depends?label=pypi%20package" alt="Package version">
    </a>
    <a href="https://pepy.tech/project/fast-depends" target="_blank">
        <img src="https://static.pepy.tech/personalized-badge/fast-depends?period=month&units=international_system&left_color=grey&right_color=blue" alt="downloads"/>
    </a>
    <br/>
    <a href="https://pypi.org/project/fast-depends" target="_blank">
        <img src="https://img.shields.io/pypi/pyversions/fast-depends.svg" alt="Supported Python versions">
    </a>
    <a href="https://github.com/Lancetnik/FastDepends/blob/main/LICENSE" target="_blank">
        <img alt="GitHub" src="https://img.shields.io/github/license/Lancetnik/FastDepends?color=%23007ec6">
    </a>
</p>

---

Documentation: https://lancetnik.github.io/FastDepends/

---

FastDepends - FastAPI Dependency Injection system extracted from FastAPI and cleared of all HTTP logic.
This is a small library which provides you with the ability to use lovely FastAPI interfaces in your own
projects or tools.

Thanks to [*fastapi*](https://fastapi.tiangolo.com/) and [*pydantic*](https://docs.pydantic.dev/) projects for this
great functionality. This package is just a small change of the original FastAPI sources to provide DI functionality in a pure-Python way.

Async and sync modes are both supported.

# For why?

This project should be extremely helpful to boost your not-**FastAPI** applications (even **Flask**, I know that u like some legacy).

Also the project can be a core of your own framework for anything. Actually, it was build for my another project - :rocket:[**Propan**](https://github.com/Lancetnik/Propan):rocket: (and [**FastStream**](https://github.com/airtai/faststream)), check it to see full-featured **FastDepends** usage example.

## Installation

```bash
pip install fast-depends
```

## Usage

There is no way to make Dependency Injection easier

You can use this library without any frameworks in both **sync** and **async** code.

### Async code

```python
import asyncio

from fast_depends import inject, Depends

async def dependency(a: int) -> int:
    return a

@inject
async def main(
    a: int,
    b: int,
    c: int = Depends(dependency)
) -> float:
    return a + b + c

assert asyncio.run(main("1", 2)) == 4.0
```

### Sync code

```python
from fast_depends import inject, Depends

def dependency(a: int) -> int:
    return a

@inject
def main(
    a: int,
    b: int,
    c: int = Depends(dependency)
) -> float:
    return a + b + c

assert main("1", 2) == 4.0
```

`@inject` decorator plays multiple roles at the same time:

* resolve *Depends* classes
* cast types according to Python annotation
* validate incoming parameters using *pydantic*

---

### Features

Synchronous code is fully supported in this package: without any `async_to_sync`, `run_sync`, `syncify` or any other tricks.

Also, *FastDepends* casts functions' return values the same way, it can be very helpful in building your own tools.

These are two main defferences from native FastAPI DI System.

---

### Dependencies Overriding

Also, **FastDepends** can be used as a lightweight DI container. Using it, you can easily override basic dependencies with application startup or in tests.

```python
from typing import Annotated

from fast_depends import Depends, dependency_provider, inject

def abc_func() -> int:
    raise NotImplementedError()

def real_func() -> int:
    return 1

@inject
def func(
    dependency: Annotated[int, Depends(abc_func)]
) -> int:
    return dependency

with dependency_provider.scope(abc_func, real_func):
    assert func() == 1
```

`dependency_provider` in this case is just a default container already declared in the library. But you can use your own the same way:

```python
from typing import Annotated

from fast_depends import Depends, Provider, inject

provider = Provider()

def abc_func() -> int:
    raise NotImplementedError()

def real_func() -> int:
    return 1

@inject(dependency_overrides_provider=provider)
def func(
    dependency: Annotated[int, Depends(abc_func)]
) -> int:
    return dependency

with provider.scope(abc_func, real_func):
    assert func() == 1
```

This way you can inherit the basic `Provider` class and define any extra logic you want!

---

### Custom Fields

If you wish to write your own FastAPI or another closely by architecture tool, you should define your own custom fields to specify application behavior.

Custom fields can be used to adding something specific to a function arguments (like a BackgroundTask) or parsing incoming objects special way. You able decide by own, why and how you will use these tools.

FastDepends grants you this opportunity a very intuitive and comfortable way.

```python
from fast_depends import inject
from fast_depends.library import CustomField

class Header(CustomField):
    def use(self, /, **kwargs: AnyDict) -> AnyDict:
        kwargs = super().use(**kwargs)
        kwargs[self.param_name] = kwargs["headers"][self.param_name]
        return kwargs

@inject
def my_func(header_field: int = Header()):
    return header_field

assert my_func(
    headers={ "header_field": "1" }
) == 1
```

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "fast-depends",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "",
    "keywords": "dependency injection,fastapi",
    "author": "",
    "author_email": "Pastukhov Nikita <diementros@yandex.ru>",
    "download_url": "https://files.pythonhosted.org/packages/ed/0d/84b2626637af2d92b059cb9068fdc0a175e911ad1de9ebc885456cc65fdc/fast_depends-2.4.1.tar.gz",
    "platform": null,
    "description": "# FastDepends\n\n<p align=\"center\">\n    <a href=\"https://github.com/Lancetnik/FastDepends/actions/workflows/tests.yml\" target=\"_blank\">\n        <img src=\"https://github.com/Lancetnik/FastDepends/actions/workflows/tests.yml/badge.svg\" alt=\"Tests coverage\"/>\n    </a>\n    <a href=\"https://coverage-badge.samuelcolvin.workers.dev/redirect/lancetnik/fastdepends\" target=\"_blank\">\n        <img src=\"https://coverage-badge.samuelcolvin.workers.dev/lancetnik/fastdepends.svg\" alt=\"Coverage\">\n    </a>\n    <a href=\"https://pypi.org/project/fast-depends\" target=\"_blank\">\n        <img src=\"https://img.shields.io/pypi/v/fast-depends?label=pypi%20package\" alt=\"Package version\">\n    </a>\n    <a href=\"https://pepy.tech/project/fast-depends\" target=\"_blank\">\n        <img src=\"https://static.pepy.tech/personalized-badge/fast-depends?period=month&units=international_system&left_color=grey&right_color=blue\" alt=\"downloads\"/>\n    </a>\n    <br/>\n    <a href=\"https://pypi.org/project/fast-depends\" target=\"_blank\">\n        <img src=\"https://img.shields.io/pypi/pyversions/fast-depends.svg\" alt=\"Supported Python versions\">\n    </a>\n    <a href=\"https://github.com/Lancetnik/FastDepends/blob/main/LICENSE\" target=\"_blank\">\n        <img alt=\"GitHub\" src=\"https://img.shields.io/github/license/Lancetnik/FastDepends?color=%23007ec6\">\n    </a>\n</p>\n\n---\n\nDocumentation: https://lancetnik.github.io/FastDepends/\n\n---\n\nFastDepends - FastAPI Dependency Injection system extracted from FastAPI and cleared of all HTTP logic.\nThis is a small library which provides you with the ability to use lovely FastAPI interfaces in your own\nprojects or tools.\n\nThanks to [*fastapi*](https://fastapi.tiangolo.com/) and [*pydantic*](https://docs.pydantic.dev/) projects for this\ngreat functionality. This package is just a small change of the original FastAPI sources to provide DI functionality in a pure-Python way.\n\nAsync and sync modes are both supported.\n\n# For why?\n\nThis project should be extremely helpful to boost your not-**FastAPI** applications (even **Flask**, I know that u like some legacy).\n\nAlso the project can be a core of your own framework for anything. Actually, it was build for my another project - :rocket:[**Propan**](https://github.com/Lancetnik/Propan):rocket: (and [**FastStream**](https://github.com/airtai/faststream)), check it to see full-featured **FastDepends** usage example.\n\n## Installation\n\n```bash\npip install fast-depends\n```\n\n## Usage\n\nThere is no way to make Dependency Injection easier\n\nYou can use this library without any frameworks in both **sync** and **async** code.\n\n### Async code\n\n```python\nimport asyncio\n\nfrom fast_depends import inject, Depends\n\nasync def dependency(a: int) -> int:\n    return a\n\n@inject\nasync def main(\n    a: int,\n    b: int,\n    c: int = Depends(dependency)\n) -> float:\n    return a + b + c\n\nassert asyncio.run(main(\"1\", 2)) == 4.0\n```\n\n### Sync code\n\n```python\nfrom fast_depends import inject, Depends\n\ndef dependency(a: int) -> int:\n    return a\n\n@inject\ndef main(\n    a: int,\n    b: int,\n    c: int = Depends(dependency)\n) -> float:\n    return a + b + c\n\nassert main(\"1\", 2) == 4.0\n```\n\n`@inject` decorator plays multiple roles at the same time:\n\n* resolve *Depends* classes\n* cast types according to Python annotation\n* validate incoming parameters using *pydantic*\n\n---\n\n### Features\n\nSynchronous code is fully supported in this package: without any `async_to_sync`, `run_sync`, `syncify` or any other tricks.\n\nAlso, *FastDepends* casts functions' return values the same way, it can be very helpful in building your own tools.\n\nThese are two main defferences from native FastAPI DI System.\n\n---\n\n### Dependencies Overriding\n\nAlso, **FastDepends** can be used as a lightweight DI container. Using it, you can easily override basic dependencies with application startup or in tests.\n\n```python\nfrom typing import Annotated\n\nfrom fast_depends import Depends, dependency_provider, inject\n\ndef abc_func() -> int:\n    raise NotImplementedError()\n\ndef real_func() -> int:\n    return 1\n\n@inject\ndef func(\n    dependency: Annotated[int, Depends(abc_func)]\n) -> int:\n    return dependency\n\nwith dependency_provider.scope(abc_func, real_func):\n    assert func() == 1\n```\n\n`dependency_provider` in this case is just a default container already declared in the library. But you can use your own the same way:\n\n```python\nfrom typing import Annotated\n\nfrom fast_depends import Depends, Provider, inject\n\nprovider = Provider()\n\ndef abc_func() -> int:\n    raise NotImplementedError()\n\ndef real_func() -> int:\n    return 1\n\n@inject(dependency_overrides_provider=provider)\ndef func(\n    dependency: Annotated[int, Depends(abc_func)]\n) -> int:\n    return dependency\n\nwith provider.scope(abc_func, real_func):\n    assert func() == 1\n```\n\nThis way you can inherit the basic `Provider` class and define any extra logic you want!\n\n---\n\n### Custom Fields\n\nIf you wish to write your own FastAPI or another closely by architecture tool, you should define your own custom fields to specify application behavior.\n\nCustom fields can be used to adding something specific to a function arguments (like a BackgroundTask) or parsing incoming objects special way. You able decide by own, why and how you will use these tools.\n\nFastDepends grants you this opportunity a very intuitive and comfortable way.\n\n```python\nfrom fast_depends import inject\nfrom fast_depends.library import CustomField\n\nclass Header(CustomField):\n    def use(self, /, **kwargs: AnyDict) -> AnyDict:\n        kwargs = super().use(**kwargs)\n        kwargs[self.param_name] = kwargs[\"headers\"][self.param_name]\n        return kwargs\n\n@inject\ndef my_func(header_field: int = Header()):\n    return header_field\n\nassert my_func(\n    headers={ \"header_field\": \"1\" }\n) == 1\n```\n",
    "bugtrack_url": null,
    "license": "",
    "summary": "FastDepends - extracted and cleared from HTTP domain logic FastAPI Dependency Injection System. Async and sync are both supported.",
    "version": "2.4.1",
    "project_urls": {
        "Documentation": "https://lancetnik.github.io/FastDepends/",
        "Homepage": "https://lancetnik.github.io/FastDepends/",
        "Source": "https://github.com/Lancetnik/FastDepends",
        "Tracker": "https://github.com/Lancetnik/FastDepends/issues"
    },
    "split_keywords": [
        "dependency injection",
        "fastapi"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a0de9133f4c41b19adc7bf342c248057c4a8755d72dd49eb6ba6c3073b6bd5ea",
                "md5": "3e1650813349641c7792b06021f04fd5",
                "sha256": "5100228ba207800c1330b18091584fc067d728c10bd223d3ace47c0567052b7f"
            },
            "downloads": -1,
            "filename": "fast_depends-2.4.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "3e1650813349641c7792b06021f04fd5",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 17347,
            "upload_time": "2024-02-25T14:27:15",
            "upload_time_iso_8601": "2024-02-25T14:27:15.755914Z",
            "url": "https://files.pythonhosted.org/packages/a0/de/9133f4c41b19adc7bf342c248057c4a8755d72dd49eb6ba6c3073b6bd5ea/fast_depends-2.4.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "ed0d84b2626637af2d92b059cb9068fdc0a175e911ad1de9ebc885456cc65fdc",
                "md5": "6814117747c98f3ad27fea4d16139632",
                "sha256": "bd688eea620f66ab27b5338bb7291d58f71445a748aa0e70321c109827d3ec8e"
            },
            "downloads": -1,
            "filename": "fast_depends-2.4.1.tar.gz",
            "has_sig": false,
            "md5_digest": "6814117747c98f3ad27fea4d16139632",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 16363,
            "upload_time": "2024-02-25T14:27:17",
            "upload_time_iso_8601": "2024-02-25T14:27:17.246111Z",
            "url": "https://files.pythonhosted.org/packages/ed/0d/84b2626637af2d92b059cb9068fdc0a175e911ad1de9ebc885456cc65fdc/fast_depends-2.4.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-02-25 14:27:17",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Lancetnik",
    "github_project": "FastDepends",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "fast-depends"
}
        
Elapsed time: 0.21639s