在同步而非非模式下使用 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。
我正在构建一个简单的 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 编码,并更改标题。没有什么对我有用。
我试图将一个名为“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) 在Flask中,来自客户端的请求可以如下处理。
对于 JSON 数据:
payload = request.get_json()
对于令牌参数:
token = request.headers.get('Authorization')
对于参数:
id = request.args.get('url', None)
FastAPI 做同样事情的方法是什么?