fastapi-routesmanager


Namefastapi-routesmanager JSON
Version 0.0.3 PyPI version JSON
download
home_page
SummaryManipulate requests before FastAPI processes them, and responses once finished.
upload_time2023-09-21 14:44:32
maintainer
docs_urlNone
author
requires_python>=3.7
licenseMIT License
keywords fastapi middleware router routes request response api
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Routes Manager for FastAPI

Manipulate requests before [FastAPI](https://github.com/tiangolo/fastapi) processes them (even before middlewares), and responses once finished.

## Installation

```console
$ pip install fastapi-routesmanager
```


## Example

Using example `HeadersLogger` from this package.

```python
from typing import Union

from fastapi import FastAPI

from fastapi_routesmanager import HeadersLogger, RouteManagersRegistry, ManagedAPIRouter
import logging

logging.basicConfig(level=logging.DEBUG)  # Needed to get DEBUG output

RouteManagersRegistry.register_route_manager(HeadersLogger)  # Register manager

app = FastAPI()

router = ManagedAPIRouter()


@router.get("/")  # Use router instead of app
def read_root():
    return {"Hello": "World"}


@router.get("/items/{item_id}")
def read_item(item_id: int, q: Union[str, None] = None):
    return {"item_id": item_id, "q": q}


app.include_router(router)  # Include the router to the app

```

<details>
<summary>Or you can register multiple managers at once</summary>

```python
RouteManagersRegistry.register_route_managers([
    HeadersLogger,
    ExceptionLogger
])
```
</details>

### Run it

```console
$ uvicorn main:app --reload
```

### Check it

Browse to http://127.0.0.1:8000 and check the server console.
You should see something like this showing the headers

```console
# DEBUG:headers_logger:Requests headers: Headers({'host': 'localhost:8000', 'user-agent': 'Mozilla Firefox', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'accept-language': 'es-AR,es;q=0.8,en-US;q=0.5,en;q=0.3', 'accept-encoding': 'gzip', 'dnt': '1', 'connection': 'keep-alive', 'upgrade-insecure-requests': '1', 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'none'})
# DEBUG:headers_logger:Response headers: MutableHeaders({'content-length': '17', 'content-type': 'application/json'})
# INFO:     127.0.0.1:49370 - "GET /1 HTTP/1.1" 200 OK
```

## Creating custom Manager

In order to create a custom manager you need to extend `RouteManager` and declare an `async def run(...)` method.

Within this method you can access the request, execute it and get the response.

```python
from fastapi_routesmanager import RouteManager
from starlette.requests import Request
from starlette.responses import Response
from typing import Callable, List, Type, Optional


class CustomManager(RouteManager):
    async def run(
            self,
            request: Request,
            call_next: Callable,
            remaining_managers: List[Type[RouteManager]],
    ) -> Optional[Response]:
        # This will run the request through FastAPI  
        response: Response = await call_next(request, remaining_managers)
        return response

```

In the `remaining_managers` list you will find all remaining managers to be run. You can modify this list to add or remove managers dynamically.

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "fastapi-routesmanager",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "fastapi,middleware,router,routes,request,response,api",
    "author": "",
    "author_email": "SirPaulO <me@sirpauloliver.com>",
    "download_url": "https://files.pythonhosted.org/packages/c2/73/118fdfb80eb93be64e5efdaa9a3630e9e916f9017732f4e4ca1b522cf4ea/fastapi_routesmanager-0.0.3.tar.gz",
    "platform": null,
    "description": "# Routes Manager for FastAPI\n\nManipulate requests before [FastAPI](https://github.com/tiangolo/fastapi) processes them (even before middlewares), and responses once finished.\n\n## Installation\n\n```console\n$ pip install fastapi-routesmanager\n```\n\n\n## Example\n\nUsing example `HeadersLogger` from this package.\n\n```python\nfrom typing import Union\n\nfrom fastapi import FastAPI\n\nfrom fastapi_routesmanager import HeadersLogger, RouteManagersRegistry, ManagedAPIRouter\nimport logging\n\nlogging.basicConfig(level=logging.DEBUG)  # Needed to get DEBUG output\n\nRouteManagersRegistry.register_route_manager(HeadersLogger)  # Register manager\n\napp = FastAPI()\n\nrouter = ManagedAPIRouter()\n\n\n@router.get(\"/\")  # Use router instead of app\ndef read_root():\n    return {\"Hello\": \"World\"}\n\n\n@router.get(\"/items/{item_id}\")\ndef read_item(item_id: int, q: Union[str, None] = None):\n    return {\"item_id\": item_id, \"q\": q}\n\n\napp.include_router(router)  # Include the router to the app\n\n```\n\n<details>\n<summary>Or you can register multiple managers at once</summary>\n\n```python\nRouteManagersRegistry.register_route_managers([\n    HeadersLogger,\n    ExceptionLogger\n])\n```\n</details>\n\n### Run it\n\n```console\n$ uvicorn main:app --reload\n```\n\n### Check it\n\nBrowse to http://127.0.0.1:8000 and check the server console.\nYou should see something like this showing the headers\n\n```console\n# DEBUG:headers_logger:Requests headers: Headers({'host': 'localhost:8000', 'user-agent': 'Mozilla Firefox', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8', 'accept-language': 'es-AR,es;q=0.8,en-US;q=0.5,en;q=0.3', 'accept-encoding': 'gzip', 'dnt': '1', 'connection': 'keep-alive', 'upgrade-insecure-requests': '1', 'sec-fetch-dest': 'document', 'sec-fetch-mode': 'navigate', 'sec-fetch-site': 'none'})\n# DEBUG:headers_logger:Response headers: MutableHeaders({'content-length': '17', 'content-type': 'application/json'})\n# INFO:     127.0.0.1:49370 - \"GET /1 HTTP/1.1\" 200 OK\n```\n\n## Creating custom Manager\n\nIn order to create a custom manager you need to extend `RouteManager` and declare an `async def run(...)` method.\n\nWithin this method you can access the request, execute it and get the response.\n\n```python\nfrom fastapi_routesmanager import RouteManager\nfrom starlette.requests import Request\nfrom starlette.responses import Response\nfrom typing import Callable, List, Type, Optional\n\n\nclass CustomManager(RouteManager):\n    async def run(\n            self,\n            request: Request,\n            call_next: Callable,\n            remaining_managers: List[Type[RouteManager]],\n    ) -> Optional[Response]:\n        # This will run the request through FastAPI  \n        response: Response = await call_next(request, remaining_managers)\n        return response\n\n```\n\nIn the `remaining_managers` list you will find all remaining managers to be run. You can modify this list to add or remove managers dynamically.\n",
    "bugtrack_url": null,
    "license": "MIT License",
    "summary": "Manipulate requests before FastAPI processes them, and responses once finished.",
    "version": "0.0.3",
    "project_urls": {
        "Bug Tracker": "https://github.com/SirPaulO/fastapi_routesmanager/issues",
        "Homepage": "https://github.com/SirPaulO/fastapi_routesmanager",
        "Repository": "https://github.com/SirPaulO/fastapi_routesmanager.git"
    },
    "split_keywords": [
        "fastapi",
        "middleware",
        "router",
        "routes",
        "request",
        "response",
        "api"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "996f780038c28bbc788d60751e4c59219bc59ab914530b8964f0ec5465d4e321",
                "md5": "c53ddcac33435bb8bc8f60a05c79762b",
                "sha256": "2f7055c702c1883442b1985b10454cd5dc68866962a3c568f39b11333ace86a9"
            },
            "downloads": -1,
            "filename": "fastapi_routesmanager-0.0.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "c53ddcac33435bb8bc8f60a05c79762b",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 4905,
            "upload_time": "2023-09-21T14:44:30",
            "upload_time_iso_8601": "2023-09-21T14:44:30.661480Z",
            "url": "https://files.pythonhosted.org/packages/99/6f/780038c28bbc788d60751e4c59219bc59ab914530b8964f0ec5465d4e321/fastapi_routesmanager-0.0.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c273118fdfb80eb93be64e5efdaa9a3630e9e916f9017732f4e4ca1b522cf4ea",
                "md5": "c01322f4fb60b1dee263a2ab25e7a221",
                "sha256": "ef2a258c0c70061de03a982c01f463d63d15e76eea114a20e9a1ac6759d96b8d"
            },
            "downloads": -1,
            "filename": "fastapi_routesmanager-0.0.3.tar.gz",
            "has_sig": false,
            "md5_digest": "c01322f4fb60b1dee263a2ab25e7a221",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 3665,
            "upload_time": "2023-09-21T14:44:32",
            "upload_time_iso_8601": "2023-09-21T14:44:32.342444Z",
            "url": "https://files.pythonhosted.org/packages/c2/73/118fdfb80eb93be64e5efdaa9a3630e9e916f9017732f4e4ca1b522cf4ea/fastapi_routesmanager-0.0.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-09-21 14:44:32",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "SirPaulO",
    "github_project": "fastapi_routesmanager",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "fastapi-routesmanager"
}
        
Elapsed time: 0.12899s