相关疑难解决方法(0)

FastAPI 以串行方式而不是并行方式运行 api 调用

我有以下代码:

import time
from fastapi import FastAPI, Request
    
app = FastAPI()
    
@app.get("/ping")
async def ping(request: Request):
        print("Hello")
        time.sleep(5)
        print("bye")
        return {"ping": "pong!"}
Run Code Online (Sandbox Code Playgroud)

如果我在本地主机上运行我的代码 - 例如http://localhost:8501/ping- 在同一浏览器窗口的不同选项卡中,我得到:

Hello
bye
Hello
bye
Run Code Online (Sandbox Code Playgroud)

代替:

Hello
Hello
bye
bye
Run Code Online (Sandbox Code Playgroud)

我已经阅读过有关使用的内容httpx,但仍然无法实现真正​​的并行化。有什么问题?

python asynchronous concurrent-processing python-asyncio fastapi

50
推荐指数
1
解决办法
4万
查看次数

以同步方式使用 FastAPI,如何获取 POST 请求的原始正文?

在同步而非非模式下使用 FastAPI async,我希望能够接收 POST 请求的原始、未更改的正文。

我能找到的所有示例都显示async代码,当我以正常同步方式尝试时,它们request.body()显示为协程对象。

XML当我通过向此端点发布一些内容来测试它时,我得到了一个500 "Internal Server Error".

from fastapi import FastAPI, Response, Request, Body

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.post("/input")
def input_request(request: Request):
    # how can I access the RAW request body here?  
    body = request.body()

    # do stuff with the body here  

    return Response(content=body, media_type="application/xml")
Run Code Online (Sandbox Code Playgroud)

这对于 FastAPI 来说是不可能的吗?

注意:简化的输入请求如下所示:

POST http://127.0.0.1:1083/input
Content-Type: application/xml

<XML>
    <BODY>TEST</BODY>
</XML>
Run Code Online (Sandbox Code Playgroud)

我无法控制输入请求的发送方式,因为我需要替换现有的 SOAP API。

python starlette fastapi

21
推荐指数
1
解决办法
2万
查看次数

FastAPI:如何将正文读取为任何有效的 json?

抱歉,不精通Python。

我还没有找到该用例的文档。我如何获取请求正文,确保它是一个有效的 Json(任何有效的 json,包括数字、字符串、布尔值和空值,而不仅仅是对象和数组)并获取实际的 Json。使用 pydantic 强制 Json 具有特定的结构。

json pydantic fastapi

20
推荐指数
3
解决办法
2万
查看次数

FastAPI 显示“msg”:“必填字段”,“类型”:“value_error.missing”

各位晚上好。我正在尝试使用 FastAPI 请求将新用户添加到我的数据库中。当我尝试通过 python 控制台应用程序执行此操作时,FastAPI 向我显示以下消息:

{
     'detail': [
         {
             'loc': ['body', 'nickname'],
             'msg': 'field required',
             'type': 'value_error.missing'
         },
         {
             'loc': ['body', 'password'],
             'msg': 'field required',
             'type': 'value_error.missing'
         },
         {
             'loc': ['body', 'email'],
             'msg': 'field required',
             'type': 'value_error.missing'
         }
    ]
}
Run Code Online (Sandbox Code Playgroud)

但是,当我执行此请求时,/docs一切正常!

这是我的 pydantic 模型:

{
     'detail': [
         {
             'loc': ['body', 'nickname'],
             'msg': 'field required',
             'type': 'value_error.missing'
         },
         {
             'loc': ['body', 'password'],
             'msg': 'field required',
             'type': 'value_error.missing'
         },
         {
             'loc': ['body', 'email'],
             'msg': 'field required',
             'type': 'value_error.missing'
         } …
Run Code Online (Sandbox Code Playgroud)

python pydantic fastapi

18
推荐指数
1
解决办法
4万
查看次数

FastAPI 帖子无法识别我的参数

我通常使用 Tornado,并尝试迁移到 FastAPI。

假设我有一个非常基本的 API,如下所示:

@app.post("/add_data")
async def add_data(data):
    return data
Run Code Online (Sandbox Code Playgroud)

当我运行以下 Curl 请求时: curl http://127.0.0.1:8000/add_data -d 'data=Hello'

我收到以下错误:

{"detail":[{"loc":["query","data"],"msg":"field required","type":"value_error.missing"}]}

所以我确信我错过了一些非常基本的东西,但我不知道那可能是什么。

python curl http-status-code-422 fastapi

12
推荐指数
1
解决办法
1万
查看次数

如何在 FastAPI 中 POST 具有单个主体参数的 JSON?

我有一个名为的文件main.py,其中POST仅使用一个输入参数(整数)进行调用。简化代码如下:

from fastapi import FastAPI

app = FastAPI()

@app.post("/do_something/")
async def do_something(process_id: int):
    # some code
    return {"process_id": process_id}
Run Code Online (Sandbox Code Playgroud)

现在,如果我运行保存在文件中的测试代码test_main.py,即:

from fastapi.testclient import TestClient
from main import app

client = TestClient(app)

def test_do_something():
    response = client.post(
        "/do_something/",
        json={
            "process_id": 16
        }
    )
    return response.json()

print(test_do_something())
Run Code Online (Sandbox Code Playgroud)

我得到:

{'detail': [{'loc': ['query', 'process_id'], 'msg': 'field required', 'type': 'value_error.missing'}]}
Run Code Online (Sandbox Code Playgroud)

我不明白这是什么错误。有必要继续呼吁POST

python fastapi

7
推荐指数
1
解决办法
8492
查看次数

如何将 JSON 数据发布到 FastAPI 并在端点内检索 JSON 数据?

我想将 JSON 对象传递到 FastAPI 后端。这是我在前端应用程序中所做的事情:

data = {'labels': labels, 'sequences': sequences}
response = requests.post(api_url, data = data)
Run Code Online (Sandbox Code Playgroud)

FastAPI 中的后端 API 如下所示:

@app.post("/api/zero-shot/")
async def Zero_Shot_Classification(request: Request):
    data = await request.json()
Run Code Online (Sandbox Code Playgroud)

但是,我收到此错误:

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Run Code Online (Sandbox Code Playgroud)

python rest fastapi streamlit

7
推荐指数
1
解决办法
1万
查看次数

FastAPI POST - 错误 422 详细信息'': ( ( loc'':(body file msg'':field required'', type'': value_error Missing)))

我想在后端读取这个 xlsx 文件。当我使用 swagger 时,我得到了它,但是当我在前端测试时,我收到错误 422 - devtools/网络详细信息'': ( ( loc'':(body file msg'':field required'', type'': value_error 丢失)))。

router = APIRouter()

@router.post('/')
async def upload_file(file: Uploadfile = File(...)):

  try:
    arquivo = await file.read()
    df_cambio = pd.read_excel(arquivo)
    cambio_dict = df_cambio.to_dict('index')
    
    print(cambio_dict)
    return{"file_name": file.filename}
  
  except Exception as e:
    exception_handler(e)
Run Code Online (Sandbox Code Playgroud)

反应->

export defaut function Dropzone() {
const [create, {isLoading}] = usePost();

const handleSubmit = (res) => {
    create('cambios', { data:res.file }})
};
if (isLoading) { return <LoadingPageSkeleton />;}

return (

<BasicForm
  initialValues={{}}
  onSubmit={handleSubmit}
> …
Run Code Online (Sandbox Code Playgroud)

python forms post typescript fastapi

6
推荐指数
1
解决办法
1万
查看次数

如何创建可以接受 Form 或 JSON 正文的 FastAPI 端点?

我想在 FastAPI 中创建一个可能接收(多部分)Form数据或JSON正文的端点。有没有办法让这样的端点接受或者检测正在接收哪种类型的数据?

python json multipartform-data starlette fastapi

6
推荐指数
1
解决办法
6025
查看次数

如何使用 ReactJS 在前端使用 Axios,在后端使用 FastAPI 下载文件?

我正在尝试创建一个docx文件并将其发送到前端客户端应用程序,以便可以将其下载到用户的本地计算机。我使用 FastAPI 作为后端。我还使用python-docx库来创建Document.

下面的代码用于创建一个docx文件并将其保存到服务器。

@app.post("/create_file")
async def create_file(data: Item):
    document = Document()
    document.add_heading("file generated", level=1)
    document.add_paragraph("test")
    document.save('generated_file.docx')
    return {"status":"Done!"}
Run Code Online (Sandbox Code Playgroud)

然后使用以下代码将创建的docx文件作为 a发送FileResponse到客户端。

@app.get("/generated_file")
async def download_generated_file():
    file_path = "generated_file.docx"
    return FileResponse(file_path, media_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document', filename=file_path)
Run Code Online (Sandbox Code Playgroud)

在客户端(我正在使用 ReactJS):

@app.post("/create_file")
async def create_file(data: Item):
    document = Document()
    document.add_heading("file generated", level=1)
    document.add_paragraph("test")
    document.save('generated_file.docx')
    return {"status":"Done!"}
Run Code Online (Sandbox Code Playgroud)

调用函数generated.docx时会下载文件。downloadFile但是,该docx文件始终已损坏并且无法打开。我尝试使用txt文件,效果很好。我需要使用docx文件,我该怎么办?

javascript web reactjs axios fastapi

5
推荐指数
1
解决办法
8170
查看次数