如何在 FastAPI 的端点视图函数中访问 APP 属性?

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

这是我的项目结构:

│   .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
│   │   │

这是最外面的,start.py 看起来像:

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)

而且,我所有的端点和视图函数都是在 training_essentials.py 和 evaluation_essentials.py 中创建的 例如,这是 training_essentials.py 的样子:

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",
        }

如何访问 APP 属性,它在我端点的视图函数中的变量?

您可以访问 request.app 作为

<b>from fastapi import Request</b>


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