### Install FastDepends Source: https://github.com/lancetnik/fastdepends/blob/main/README.md Install the FastDepends package using pip. This is the only setup required to use the library. ```bash pip install fast-depends ``` -------------------------------- ### Install Development Dependencies with uv Source: https://github.com/lancetnik/fastdepends/blob/main/CONTRIBUTING.md Install all development dependencies using the uv package manager. ```bash uv sync --group dev ``` -------------------------------- ### Full FastDepends Starlette Example Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/advanced/starlette.md A complete example combining custom fields, dependency injection, and a Starlette application. ```python from fast_depends import inject, dependency_provider, wrap_starlette, Depends from starlette.requests import Request from starlette.responses import PlainTextResponse from starlette.routing import Route from starlette.applications import Starlette from typing import Annotated @inject def get_request_kwargs(request: Request): return request.path_params @dependency_provider def Path(): return lambda: ... def get_user(user_id: int = Path()): return f"user {user_id}" @wrap_starlette async def hello(user: str = Depends(get_user)): return PlainTextResponse(f"Hello, {user}!") @wrap_starlette async def get_user_annotated(user: Annotated[int, Path()]): return PlainTextResponse(f"Hello, {user}!") app = Starlette(debug=True, routes=[ Route("/{user_id}", hello) ]) ``` -------------------------------- ### Install Dependencies with pip Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/contributing.md Install the latest pip version and then install FastDepends and its development dependencies in editable mode. ```bash python -m pip install -U pip ``` ```bash pip install --group dev -e . ``` -------------------------------- ### Install Development Dependencies with Pip Source: https://github.com/lancetnik/fastdepends/blob/main/CONTRIBUTING.md Install all development dependencies and the local FastDepends package in editable mode using pip. ```bash pip install --group dev -e . ``` -------------------------------- ### Sync Dependency Injection Example Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/index.md Demonstrates synchronous dependency injection using the @inject decorator. This code can be run directly without an event loop. ```python from fast_depends import inject, Depends def sync_dependency_provider(): return "sync dependency" @inject def sync_func(dependency: str = Depends(sync_dependency_provider)): return dependency if __name__ == "__main__": result = sync_func() print(result) ``` -------------------------------- ### Basic Async Dependency Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/index.md Example of an asynchronous dependency declaration and usage. Async runtimes support both sync and async dependencies. ```python from fast_depends import Depends, inject async def async_dependency() -> str: return "hello" @inject async def main(dep: str = Depends(async_dependency)): return dep ``` -------------------------------- ### Basic Sync Dependency Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/index.md Example of a synchronous dependency declaration and usage. Ensure only sync dependencies are used in sync runtimes. ```python from fast_depends import Depends, inject def sync_dependency() -> str: return "hello" @inject def main(dep: str = Depends(sync_dependency)): return dep ``` -------------------------------- ### FastDepends Core Logic Example Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/works.md Illustrates the general workflow of FastDepends, including model building, argument validation, dependency execution, and return type casting. This is a conceptual representation, not the actual implementation. ```python from typing import Dict, Any from fastapi import Depends from pydantic import BaseModel class User(BaseModel): username: str def get_user() -> User: return User(username="john") def process_data(user: User = Depends(get_user)) -> Dict[str, Any]: return {"message": f"Hello {user.username}"} ``` -------------------------------- ### Async Dependency Injection Example Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/index.md Demonstrates asynchronous dependency injection using the @inject decorator. Ensure you have an async event loop running to execute this code. ```python from fast_depends import inject, Depends def async_dependency_provider(): return "async dependency" @inject def async_func(dependency: str = Depends(async_dependency_provider)): return dependency async def main(): result = await async_func() print(result) if __name__ == "__main__": import asyncio asyncio.run(main()) ``` -------------------------------- ### Non-Annotated Dependency Example Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/annotated.md This example shows a common pattern with duplicated dependency declarations. ```python from fastapi import FastAPI, Depends app = FastAPI() class User: def __init__(self, username: str): self.username = username def get_user(username: str = "John Doe") -> User: return User(username=username) @app.get("/users/me") def read_users_me(user: User = Depends(get_user)): return user @app.get("/users/{username}") def read_user(user: User = Depends(get_user)): return user ``` -------------------------------- ### Upgrade Pip in Virtual Environment Source: https://github.com/lancetnik/fastdepends/blob/main/CONTRIBUTING.md Ensure you have the latest version of pip installed within your activated virtual environment. ```bash python -m pip install --upgrade pip ``` -------------------------------- ### Starlette Handler with Path Dependency Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/advanced/starlette.md Example of a Starlette handler using a Path dependency defined with FastDepends. ```python def get_user(user_id: int = Path()): return f"user {user_id}" ``` -------------------------------- ### FastDepends Argument Parsing Example Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/annotated.md Highlights how FastDepends parses positional arguments based on their position, which can lead to errors if not used carefully with Annotated. ```python from typing import Annotated class User: def __init__(self, username: str): self.username = username def get_user(username: str = "John Doe") -> User: return User(username=username) CurrentUser = Annotated[User, Depends(get_user)] def func(user: CurrentUser, user_id: int | None = None): ... # Function body ``` -------------------------------- ### Async Dependency Injection Example Source: https://github.com/lancetnik/fastdepends/blob/main/README.md Demonstrates using FastDepends with asynchronous functions. The `@inject` decorator resolves dependencies and casts types. Ensure `asyncio` is imported for running 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 ``` -------------------------------- ### Override Default Dependencies Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/index.md Example of overriding a default dependency using the `dependency_provider.scope` context manager. This is useful for testing or configuring dependencies. ```python from typing import Annotated from fast_depends import Depends, dependency_provider, inject def abc_func() -> int: raise 2 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 ``` -------------------------------- ### Sync Dependency Injection Example Source: https://github.com/lancetnik/fastdepends/blob/main/README.md Illustrates using FastDepends with synchronous functions. The `@inject` decorator handles dependency resolution and type casting without requiring `asyncio`. ```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 ``` -------------------------------- ### Integrate FastDepends with Starlette Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/usages.md Example of using FastDepends with Starlette. It's recommended to wrap validation errors in a custom response for production environments. ```python from starlette.applications import Starlette from starlette.routing import Route from fastdepends.fastdepends import FastDepends def process_data(data: dict): return {"message": "Data processed successfully", "data": data} async def homepage(request): return await FastDepends(request_body=dict).call(process_data) routes = [ Route("/process", endpoint=homepage, methods=["POST"]), ] app = Starlette(routes=routes) ``` -------------------------------- ### Integrate FastDepends with Flask Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/usages.md Example of using FastDepends within a Flask application. Ensure to handle Pydantic's ValidationError for production use. ```python from flask import Flask from fastdepends.fastdepends import FastDepends app = Flask(__name__) def process_data(data: dict): return {"message": "Data processed successfully", "data": data} @app.route("/process", methods=["POST"]) def process_route(): return FastDepends(request_body=dict).call(process_data) if __name__ == "__main__": app.run(debug=True) ``` -------------------------------- ### Use a Custom Header Field Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/advanced/index.md This example shows how to use the custom `Header` field to parse incoming headers and pass them as an argument to the function. The `param_name` is set to 'header_field'. ```python from fastapi import FastAPI from fast_depends.dependencies import inject app = FastAPI() @app.get("/") @inject async def main(header_field=Header(param_name="header_field")): return header_field ``` -------------------------------- ### Define and Use a Custom Header Field in FastDepends Source: https://github.com/lancetnik/fastdepends/blob/main/README.md Create a custom field by inheriting from `CustomField` and overriding the `use` method. This example shows how to extract a header value and use it as a function argument. Ensure the necessary headers are provided in the call. ```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 ``` -------------------------------- ### Using Any Method as Dependency Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/classes.md Demonstrates using any method of a class as a dependency. Async methods are supported for this type of dependency. ```python from fastapi import FastAPI from fastdepends.dependencies import Depends class MyDependency: def __init__(self, value: int = 1) -> None: self.value = value async def async_method(self, request_value: str = "default") -> str: return f"async_method-{self.value}-{request_value}" app = FastAPI() @app.get("/") def main( dependency: str = Depends(MyDependency(value=10).async_method) ): return {"value": dependency} ``` -------------------------------- ### Using Classes as Dependencies Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/classes.md Demonstrates the basic usage of classes as dependencies in FastDepends. ```python from fastapi import FastAPI from fastdepends.dependencies import Depends class MyDependency: def __init__(self, value: int = 1) -> None: self.value = value app = FastAPI() @app.get("/") def main( dependency: MyDependency = Depends(MyDependency) ): return {"value": dependency.value} ``` -------------------------------- ### Run Tests with Script Source: https://github.com/lancetnik/fastdepends/blob/main/CONTRIBUTING.md Execute the test suite using the provided test script. ```bash bash ./scripts/test.sh ``` -------------------------------- ### Annotated Dependency for Reusability Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/annotated.md Demonstrates creating a reusable Annotated dependency to avoid duplication. ```python from typing import Annotated from fastapi import FastAPI, Depends app = FastAPI() class User: def __init__(self, username: str): self.username = username def get_user(username: str = "John Doe") -> User: return User(username=username) CurrentUser = Annotated[User, Depends(get_user)] @app.get("/users/me") def read_users_me(user: CurrentUser): return user @app.get("/users/{username}") def read_user(user: CurrentUser): return user ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/lancetnik/fastdepends/blob/main/CONTRIBUTING.md Execute the test suite with coverage output using the provided coverage script. ```bash bash ./scripts/test-cov.sh ``` -------------------------------- ### Override Dependencies with Default Provider Source: https://github.com/lancetnik/fastdepends/blob/main/README.md Shows how to override a dependency using the default `dependency_provider`. This is useful for testing or application startup configurations. The `scope` context manager temporarily replaces the dependency. ```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 ``` -------------------------------- ### Activate Virtual Environment Source: https://github.com/lancetnik/fastdepends/blob/main/CONTRIBUTING.md Activate the created virtual environment to use its isolated Python interpreter and packages. ```bash source ./venv/bin/activate ``` -------------------------------- ### Create and Use Custom Dependency Provider Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/overrides.md Define a custom `Provider` instance to manage dependency overrides. This allows for localized control over which dependencies are overridden and when, using a scope context manager. ```python from typing import Annotated from fast_depends import Depends, Provider, inject provider = Provider() def abc_func() -> int: raise 2 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 ``` -------------------------------- ### Nested Sync Dependencies Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/index.md Demonstrates nested dependencies in a synchronous context. `FastDepends` caches dependency responses within a single `@inject` call. ```python def another_dependency() -> str: return "nested" def sync_dependency(dep: str = Depends(another_dependency)) -> str: return dep @inject def main(dep: str = Depends(sync_dependency)): return dep ``` -------------------------------- ### Annotated Usage with Path Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/advanced/starlette.md Demonstrates using Annotated with Path for dependency injection in Starlette. ```python from typing import Annotated @wrap_starlette async def get_user(user: Annotated[int, Path()]): return PlainTextResponse(f"Hello, {user}!") ``` -------------------------------- ### Override Dependencies with Custom Provider Source: https://github.com/lancetnik/fastdepends/blob/main/README.md Demonstrates overriding dependencies using a custom `Provider` instance. This allows for more flexible DI container management. The `scope` method on the custom provider is used for temporary overrides. ```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 ``` -------------------------------- ### Run Pytests Source: https://github.com/lancetnik/fastdepends/blob/main/CONTRIBUTING.md Execute the test suite using pytest in the current FastDepends application and Python environment. ```bash pytest tests ``` -------------------------------- ### Nested Async Dependencies Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/index.md Demonstrates nested dependencies in an asynchronous context. `FastDepends` caches dependency responses within a single `@inject` call. ```python async def another_dependency() -> str: return "nested" async def async_dependency(dep: str = Depends(another_dependency)) -> str: return dep @inject async def main(dep: str = Depends(async_dependency)): return dep ``` -------------------------------- ### Create Virtual Environment with venv Source: https://github.com/lancetnik/fastdepends/blob/main/CONTRIBUTING.md Use this command to create an isolated Python virtual environment in a directory named 'venv'. ```bash python -m venv venv ``` -------------------------------- ### Database Dependency with Yield (Before Call) Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/yield.md Code executed before the original function call. This is useful for setting up resources like database connections. ```python from fastdepends.dependencies import Depends def db_session(): db = DbSession() yield db db.close() def main(db: DbSession = Depends(db_session)): print(db) ``` -------------------------------- ### Using Classmethod or Staticmethod as Dependency Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/classes.md Utilizes classmethods or staticmethods as dependencies, which can be helpful for OOP patterns like Strategy. ```python from fastapi import FastAPI from fastdepends.dependencies import Depends class MyDependency: def __init__(self, value: int = 1) -> None: self.value = value @classmethod def class_method(cls, request_value: str = "default") -> str: return f"classmethod-{request_value}" @staticmethod def static_method(request_value: str = "default") -> str: return f"staticmethod-{request_value}" app = FastAPI() @app.get("/class-method") def main_class_method( dependency: str = Depends(MyDependency.class_method) ): return {"value": dependency} @app.get("/static-method") def main_static_method( dependency: str = Depends(MyDependency.static_method) ): return {"value": dependency} ``` -------------------------------- ### Run Pytests Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/contributing.md Execute the project's tests using `pytest` or custom shell scripts. The `test-cov.sh` script includes coverage output. ```bash pytest tests ``` ```bash bash ./scripts/test.sh ``` ```bash bash ./scripts/test-cov.sh ``` -------------------------------- ### Chained Custom Field Execution Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/advanced/index.md Shows how multiple custom fields are executed sequentially. The `kwargs` returned by the first custom field's `use` method become the input for the next custom field's `use` method. ```python @inject def func(field1 = Header(), field2 = Header()): ... ``` -------------------------------- ### Annotated with Default Value Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/annotated.md Illustrates using Annotated with a default value, which is a valid Python construct. ```python from typing import Annotated class User: def __init__(self, username: str): self.username = username def get_user(username: str = "John Doe") -> User: return User(username=username) CurrentUser = Annotated[User, Depends(get_user)] def func(user_id: int | None = None, user: CurrentUser = None): ... # Function body ``` -------------------------------- ### Override Dependency for Testing Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/overrides.md Use `dependency_provider.dependency_overrides` to substitute original dependencies with custom ones during tests. This is useful for external services or complex logic that should not be executed in a test environment. ```python from fast_depends import Depends, dependency_provider def original_dependency() -> str: return "original" def override_dependency() -> str: return "override" def test_dependency(dep: str = Depends(original_dependency)) -> str: return dep # Override the dependency dependency_provider.dependency_overrides = { original_dependency: override_dependency } # The test_dependency will now use the override assert test_dependency() == "override" # Clean up overrides if necessary dependency_provider.dependency_overrides = {} ``` -------------------------------- ### Using Class Initializer as Dependency Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/classes.md Injects an object created by the class initializer as a dependency. Ensure to use `Any` annotation if the dependency is not a pydantic.BaseModel subclass. ```python from typing import Any from fastapi import FastAPI from fastdepends.dependencies import Depends class MyDependency: def __init__(self, value: int = 1) -> None: self.value = value app = FastAPI() @app.get("/") def main( dependency: Any = Depends(MyDependency) ): return {"value": dependency.value} ``` -------------------------------- ### Dependency Caching Control Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/index.md Shows how to disable dependency caching by setting `cache=False` in `Depends`. This forces the dependency to execute each time it's called. ```python from fast_depends import Depends, inject def sync_dependency() -> str: return "hello" @inject def main(dep: str = Depends(sync_dependency, cache=False)): return dep ``` -------------------------------- ### Sync Dependency Declaration Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/index.md Declaring a simple synchronous dependency that can be any callable object. ```python def sync_dependency() -> str: return "hello" ``` -------------------------------- ### Using __call__ Method as Dependency Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/classes.md Specifies dependency behavior using the __call__ method of an already initialized class object. ```python from fastapi import FastAPI from fastdepends.dependencies import Depends class MyDependency: def __init__(self, value: int = 1) -> None: self.value = value def __call__(self, request_value: str = "default") -> str: return f"{self.value}-{request_value}" app = FastAPI() @app.get("/") def main( dependency: str = Depends(MyDependency(value=10)) ): return {"value": dependency} ``` -------------------------------- ### Guaranteed Cleanup with Yield Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/yield.md To guarantee that cleanup code (like closing a database connection) is executed, even if errors occur, structure your generator as shown. The `yield` statement is placed strategically to ensure execution flow. ```python from fastdepends.dependencies import Depends def db_session(): db = DbSession() try: yield db finally: db.close() def main(db: DbSession = Depends(db_session)): print(db) ``` -------------------------------- ### Declare Custom Path Field Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/advanced/starlette.md Define a custom field for path parameters using FastDepends. ```python from fast_depends import dependency_provider @dependency_provider def Path(): return lambda: ... ``` -------------------------------- ### Annotated Variants with Field and Depends Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/annotated.md Shows how to use Annotated with both Field and Depends for more complex dependency definitions. ```python from typing import Annotated from fastapi import FastAPI, Depends from pydantic import Field app = FastAPI() class User: def __init__(self, username: str): self.username = username def get_user(username: str = "John Doe") -> User: return User(username=username) CurrentUser = Annotated[User, Depends(get_user)] @app.get("/users/me") def read_users_me( user: CurrentUser, user_id: Annotated[int, Field(gt=0)] ): return user @app.get("/users/{username}") def read_user(user: CurrentUser): return user ``` -------------------------------- ### Declare a Custom Field Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/advanced/index.md To create a custom field, import `CustomField` from `fast_depends.library` and implement the `use` method. This method handles the logic for parsing and transforming arguments. ```python from fast_depends.library import CustomField class Header(CustomField): async def use(self, **kwargs: AnyDict) -> AnyDict: pass ``` -------------------------------- ### Async Dependency Declaration Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/index.md Declaring a simple asynchronous dependency that can be any callable object. ```python async def async_dependency() -> str: return "hello" ``` -------------------------------- ### Usage with Starlette Application Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/advanced/starlette.md Integrate custom FastDepends fields into a Starlette application. ```python from fast_depends import wrap_starlette, Depends from starlette.responses import PlainTextResponse from starlette.routing import Route from starlette.applications import Starlette @wrap_starlette async def hello(user: str = Depends(get_user)): return PlainTextResponse(f"Hello, {user}!") app = Starlette(debug=True, routes=[ Route("/{user_id}", hello) ]) ``` -------------------------------- ### Define and Use a Custom Field for Headers Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/index.md Demonstrates creating a `Header` custom field that extracts a specific header value from incoming request headers. This field can be used to inject header values directly into function arguments. ```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 ``` -------------------------------- ### Annotated with Required Field Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/annotated.md Demonstrates using Annotated with pydantic.Field to enforce a required argument. ```python from typing import Annotated from pydantic import Field class User: def __init__(self, username: str): self.username = username def get_user(username: str = "John Doe") -> User: return User(username=username) CurrentUser = Annotated[User, Depends(get_user)] UserId = Annotated[int, Field(...)] # Field(...) is a required def func(user_id: UserId, user: CurrentUser): ... # Function body ``` -------------------------------- ### Dependency Type Casting Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/index.md Illustrates FastDepends' automatic type casting for dependency return values and injected parameters. The return type is cached and casted multiple times if used in several functions. ```python from fast_depends import inject, Depends def simple_dependency(a: int, b: int = 3) -> str: return a + b # cast 'return' to str first time @inject def method(a: int, d: int = Depends(simple_dependency)): # cast 'd' to int second time return a + d assert method("1") == 5 ``` -------------------------------- ### Sync Dependency Usage Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/index.md Using `Depends` to declare a synchronous dependency for a function. The dependency's result is automatically injected. ```python @inject def main(dep: str = Depends(sync_dependency)): return dep ``` -------------------------------- ### Async Dependency Usage Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/index.md Using `Depends` to declare an asynchronous dependency for an async function. The dependency's result is automatically injected. ```python @inject async def main(dep: str = Depends(async_dependency)): return dep ``` -------------------------------- ### Handle Request-Specific Fields in Starlette Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/advanced/starlette.md Starlette passes the request object to handlers. FastDepends requires unwrapping the request to kwargs for use. ```python from fast_depends import inject from starlette.requests import Request @inject def get_request_kwargs(request: Request): return request.path_params ``` -------------------------------- ### Custom Field Argument Transformation Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/advanced/index.md Illustrates how a custom field transforms `kwargs`. The `Header` field extracts a value from 'headers' and adds it as a new argument 'field' to the `kwargs` passed to the original function. ```python original_kwargs = { "headers": { "field": 1 }} new_kwargs = Header().set_param_name("field").use(**kwargs) # new_kwargs = { # "headers": { "field": 1 }, # "field": 1 <-- new field from Header # } original_function(**new_kwargs) ``` -------------------------------- ### Use Pytest Fixture for Dependency Overrides Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/overrides.md Employ a pytest fixture to manage dependency overrides within specific test scopes. This prevents global overrides and ensures that only relevant tests are affected. ```python from typing import Annotated from fast_depends import Depends, dependency_provider import pytest def original_dependency() -> str: return "original" def override_dependency() -> str: return "override" def test_dependency(dep: Annotated[str, Depends(original_dependency)]) -> str: return dep @pytest.fixture(scope="function", autouse=True) def override_deps(): dependency_provider.dependency_overrides[original_dependency] = override_dependency yield dependency_provider.dependency_overrides.pop(original_dependency) def test_something(): assert test_dependency() == "override" ``` -------------------------------- ### Custom Field Parameters: Cast Argument Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/advanced/index.md Demonstrates how to configure a custom field with `cast=False` to disable Pydantic typecasting for specific arguments. This is useful when annotating fields with non-Pydantic compatible types. ```python from fast_depends.library import CustomField class Header(CustomField): cast: bool = False async def use(self, **kwargs: AnyDict) -> AnyDict: pass ``` -------------------------------- ### Use Pydantic Field for Argument Validation Source: https://github.com/lancetnik/fastdepends/blob/main/docs/docs/tutorial/validations.md Use Pydantic's `Field` to define validation rules for function arguments injected by FastDepends. The `max_length` parameter is used here to enforce a maximum string length. ```python from pydantic import Field from fast_depends import inject @inject def func(a: str = Field(..., max_length=32)): ... ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.