Skip to main content

No project description provided

Project description

fastapi-wraps

Python 3.10 codecov license

functools.wraps for endpoints decorators in FastAPI.

It updates the signature of the wrapped function with parameters defined in the decorator's wrapper function. All parameters of the wrapper function should have defaults assigned.

It's advised to name the parameter with some prefix, for example __, to avoid any name conflicts in decorated functions.

To use the Request object in the decorator's wrapper function use __request: Request = Depends(get_request)

Installation

pip install fastapi-wraps

Example

def save_request(
    endpoint: Callable[P, Awaitable[RT]],
) -> Callable[P, Awaitable[RT]]:
    @fastapi_wraps(endpoint)
    async def wrapper(
        *args: Any,
        __request: Request = Depends(get_request),
        __db: Db = Depends(get_db),
        **kwargs: Any,
    ) -> RT:
        __db.save(__request)
        response = await endpoint(*args, **kwargs)
        return response

    return wrapper


app = FastAPI()


@app.get("/")
@save_request
async def hello() -> str:
    return "hello"

Why?

To use dependencies provided by FastAPI's DI framework all dependencies have to be declared in the signature of the endpoint. Hence, the decorator cannot simply use functools.wraps, as functools.wraps maintains the signature of the wrapped function. The fastapi_wraps decorator takes updates the resulting signature by merging parameters from the wrapper and the wrapped function.

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-wraps-0.1.4.tar.gz (3.8 kB view hashes)

Uploaded Source

Built Distribution

fastapi_wraps-0.1.4-py3-none-any.whl (4.5 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page