How to access APP properties inside my endpoint view function in FastAPI?

Viewed 1454

Here is my project structure:

│   .gitignore
│   README.md
│   requirements.txt
│   start.py
│
├───app
│   │   main.py
│   │
│   ├───apis
│   │   └───v1
│   │       │   __init__.py
│   │       │
│   │       │
│   │       ├───routes
│   │       │   │   evaluation_essentials.py
│   │       │   │   training_essentials.py
│   │       │
│   │
│   ├───models
│   │   │   request_response_models.py
│   │   │   __init__.py
│   │   │

This is what the outermost, start.py looks like:

import uvicorn

if __name__ == "__main__":

    from fastapi import Depends, FastAPI
    from app.apis.v1 import training_essentials, evaluation_essentials

    app = FastAPI(
        title="Some ML-API",
        version="0.1",
        description="API Contract for Some ML API",
        extra=some_important_variable
    )

    app.include_router(training_essentials.router)
    app.include_router(evaluation_essentials.router)

    uvicorn.run(app, host="0.0.0.0", port=60096)

And, all my endpoints and viewfunctions have been created in training_essentials.py and evaluation_essentials.py for example, this is what training_essentials.py looks like:

from fastapi import APIRouter
from fastapi import FastAPI, HTTPException, Query, Path
from app.models import (
    TrainingCommencement,
    TrainingCommencementResponse,
)

router = APIRouter(
    tags=["Training Essentials"],
)

@router.post("/startTraining", response_model=TrainingCommencementResponse)
async def start_training(request_body: TrainingCommencement):
    logger.info("Starting the training process")

    ## HOW TO ACCESS APP HERE?
    ## I WANT TO DO SOMETHING LIKE:
    ## some_important_variable = app.extra
    ## OR SOMETHING LIKE
    ## title = app.title

    return {
        "status_url": "some-status-url",
        }

How do I access APP properties, its variables inside that viewfunction in my endpoint?

1 Answers

You can access the request.app as

from fastapi import Request


@router.post("something")
def some_view_function(request: Request):
    fast_api_app = request.app
    return {"something": "foo"}
Related