json 在POST上使用pydantic时无法处理实体

hivapdat  于 2023-02-26  发布在  其他
关注(0)|答案(1)|浏览(169)

我尝试使用浏览器将一些数据POST到API方法中。当我使用fastAPI'sRequest对象时,一切正常。但当我使用一个迂腐的模型时,我得到:
422 (Unprocessable Entity)
我已经用curl测试了我的代码,一切正常。
下面是我的fastAPI:

from typing import Optional

from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware

from pydantic import BaseModel

import uvicorn

app = FastAPI()

origins = ["*"]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = 'N/A'

@app.post("/test_request")
async def create_item(request:Request):
  json = request.json()
  return await json

@app.post("/test_pydantic")
async def create_item(item:Item):
  return item

if __name__ == '__main__':
    uvicorn.run(app='main:app', reload=True, debug=True)

这是我的index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <h1>test</h1>
    <script>
        const person = {
            name: 'XXX',
            description: 'XXX Desc',
            price:200,
            tax: 400123598
        }

        fetch('http://127.0.0.1:8000/test_request', {
            method: 'POST',
            body: JSON.stringify(person),
            contentType: "application/json",
            dataType: 'json',
        }).then(function(respones) {
            return respones.json();
        }).then(function(data) {
            console.log('Using request', data);
        })

        fetch('http://127.0.0.1:8000/test_pydantic', {
            method: 'POST',
            body: JSON.stringify(person),
            contentType: "application/json",
            dataType: 'json',
        }).then(function(respones) {
            return respones.json();
        }).then(function(data) {
            console.log('Using pydantic', data);
        })
</script>

</body>

</html>

当从浏览器调用test_pydantic时,我得到了422

vxqlmq5t

vxqlmq5t1#

当使用JSON数据调用fetch时,您没有设置正确的content-typecontent-type头位于headers键下:

fetch('http://127.0.0.1:8000/test_pydantic', {
    method: 'POST',
    body: JSON.stringify(person),
    headers: {"content-type": "application/json"},
    dataType: 'json',
}).then(function(respones) {
    return respones.json();
}).then(function(data) {
    console.log('Using pydantic', data);
})

相关问题