python - 如何在 FastAPI 的端点 View 函数中访问 APP 属性?

标签 python python-3.x rest 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)

而且,我所有的端点和 View 函数都已在 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 属性,它在我端点的 View 函数中的变量?

最佳答案

您可以访问 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"}

关于python - 如何在 FastAPI 的端点 View 函数中访问 APP 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66596151/

相关文章:

python - Kafka-python 获取主题的分区数

python-3.x - Pandas :转换和复制 Pandas 中的某些行

休息内容协商和缓存

rest - 从 REST API 创建作业返回请求属性名称错误

c++ - PyS60 与塞类 C++

python - 使用 Pandas 创建带 Series 的 DataFrame,导致内存错误

python - 如何使用 python 查找网站的原始标题?

angular - 连续休息 API http 调用 Angular 4

python - 在 Ubuntu 14 LTS 中的 python 3.4.2 中打开 tkinter

Python-3 : Why this following code returns none in print statement?