相关疑难解决方法(0)

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

抱歉,不精通Python。

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

json pydantic fastapi

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

Python:带有 post 请求的 FastAPI 错误 422

我正在构建一个简单的 API 来测试数据库。当我使用 get request 时一切正常,但如果我更改为 post,我会收到“无法处理的实体”错误:

这是 FastAPI 代码:

from fastapi import FastAPI

app = FastAPI()

@app.post("/")
def main(user):
    return user
Run Code Online (Sandbox Code Playgroud)

然后,我的请求使用 javascript

let axios = require('axios')

data = { 
    user: 'smith' 
}

axios.post('http://localhost:8000', data)
    .then(response => (console.log(response.url)))
Run Code Online (Sandbox Code Playgroud)

并使用 Python

import requests

url = 'http://127.0.0.1:8000'
data = {'user': 'Smith'}

response = requests.post(url, json=data)
print(response.text)
Run Code Online (Sandbox Code Playgroud)

我也尝试解析为 json,使用 utf-8 编码,并更改标题。没有什么对我有用。

python python-requests axios fastapi

15
推荐指数
5
解决办法
3万
查看次数

如何将 JSON 数据从 JavaScript 前端发布到 FastAPI 后端?

我试图将一个名为“ethAddress”的值从客户端的输入表单传递到 FastAPI,以便我可以在函数中使用它来生成 matplotlib 图表。

我正在使用 fetch 将输入的文本发布到 Charts.tsx 文件中:

   fetch("http://localhost:8000/ethAddress", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(ethAddress),
    }).then(fetchEthAddresses);
Run Code Online (Sandbox Code Playgroud)

然后我的 api.py 文件设置如下:

#imports
app = FastAPI()

@app.get("/ethAddress")
async def get_images(background_tasks: BackgroundTasks, ethAddress: str):
    
    image = EthBalanceTracker.get_transactions(ethAddress)
    img_buf = image
    background_tasks.add_task(img_buf.close)
    headers = {'Content-Disposition': 'inline; filename="out.png"'}
    return Response(img_buf.getvalue(), headers=headers, media_type='image/png')


@app.post("/ethAddress")
async def add_ethAddress(ethAddress: str):
    return ethAddress
Run Code Online (Sandbox Code Playgroud)

据我了解,我使用请求将请求正文中的“ethAddress”从客户端传递到后端fetch POST,然后我可以访问@app.post在 FastAPI 中使用已发布的值。然后我将该值作为字符串返回。然后我在路线中使用它GET来生成图表。

我收到此错误:

INFO:     127.0.0.1:59821 - "POST /ethAddress HTTP/1.1" 422 Unprocessable Entity
INFO:     127.0.0.1:59821 …
Run Code Online (Sandbox Code Playgroud)

python reactjs next.js fastapi

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

标签 统计

fastapi ×3

python ×2

axios ×1

json ×1

next.js ×1

pydantic ×1

python-requests ×1

reactjs ×1