快速API,在发布请求中接受数组

时间:2020-09-06 11:42:40

标签: python fastapi frozenset

我正在尝试学习如何使用Fast API库。 我正在尝试使用docsstate中的Frozenset来接受帖子中的数组,但是它似乎不起作用。

import logging

from fastapi import FastAPI, BackgroundTasks
from worker.celery_app import celery_app

log = logging.getLogger(__name__)

app = FastAPI()


def celery_on_message(body):
    """
    Logs the initiation of the endpoint
    """
    log.warn(body)


def background_on_message(task):
    """
    logs the function when it is added to queue
    """
    log.warn(task.get(on_message=celery_on_message, propagate=False))


@app.get("/")
async def root(stocks: frozenset, background_task: BackgroundTasks):
    """
    :param stocks: stocks  to be analyzed
    :param background_task: initiate the tasks queue
    :type background_task: starlette.background.BackgroundTasks
    :return:
    """
    task_name = None

    # set correct task name based on the way you run the example
    log.log(level=1, msg=f'{stocks}')
    task_name = "app.app.worker.celery_worker.compute_stock_indicators"

    task = celery_app.send_task(task_name, args=[stocks])
    background_task.add_task(background_on_message, task)

    return {"message": "Stocks analyzed"}

当我使用招摇的文档发送请求时:

curl -X GET "http://127.0.0.1:8000/?stocks=wix&stocks=amzn" -H  "accept: application/json"

响应为:

{
  "detail": [
    {
      "loc": [
        "query",
        "stocks"
      ],
      "msg": "value is not a valid frozenset",
      "type": "type_error.frozenset"
    }
  ]
}

1 个答案:

答案 0 :(得分:0)

我认为有一个小错误

您正尝试发送 POST 请求,但是您只有 GET 端点

@app.post("/")

这应该可以解决此问题,但是,当使用“类型”进行注释时,请使用键入

from typing import FrozenSet


@app.post("/")
async def root(stocks: FrozenSet, background_task: BackgroundTasks):
万维网(W3)现在也支持

通过 GET 请求接收正文,但也强烈建议不要这样做。参见W3出版物。 OpenAPI在请求中包含正文信息,OpenAPI在下一发行版中将支持它,但SwaggerUI尚不支持。