如何在FastAPI中访问my endpoint view函数中的应用程序属性?

2024-05-18 12:40:23 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的项目结构:

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

如何访问应用程序属性及其在端点的viewfunction中的变量


Tags: frompyimportapiapptitlemodelstraining
1条回答
网友
1楼 · 发布于 2024-05-18 12:40:23

您可以按以下方式访问request.app

from fastapi import Request


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

相关问题 更多 >

    热门问题