相关疑难解决方法(0)

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万
查看次数

FastAPI GET 端点返回“405 method not allowed”响应

FastAPI 中的端点GET返回正确的结果,但405 method not allowedcurl -I使用时返回。所有GET端点都会发生这种情况。因此,应用程序正在运行,但负载均衡器对应用程序的运行状况检查失败。

有什么建议可能是错误的吗?

代码

@app.get('/health')
async def health():
    """
    Returns health status
    """
    return JSONResponse({'status': 'ok'})
Run Code Online (Sandbox Code Playgroud)

结果

curl http://172.xx.xx.xx:8080
Run Code Online (Sandbox Code Playgroud)

返回标头

curl -I http://172.xx.xx.xx:8080
Run Code Online (Sandbox Code Playgroud)

python rest http-status-code-405 fastapi

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

如何在 FastAPI 中使用 Pydantic 模型定义查询参数?

我试图有一个像这样的端点/services?status=New

status将是 New或者Old

这是我的代码:

from fastapi import APIRouter, Depends
from pydantic import BaseModel
from enum import Enum

router = APIRouter()

class ServiceStatusEnum(str, Enum):
    new = "New"
    old = "Old"


class ServiceStatusQueryParam(BaseModel):
    status: ServiceStatusEnum


@router.get("/services")
def get_services(
  status: ServiceStatusQueryParam = Query(..., title="Services", description="my desc"),
):
    pass #my code for handling this route.....
Run Code Online (Sandbox Code Playgroud)

结果是我收到一个似乎与此问题相关的错误

错误说AssertionError: Param: status can only be a request body, using Body()


然后我找到了这里解释的另一个解决方案。

所以,我的代码将是这样的:

from fastapi import APIRouter, Depends
from pydantic …
Run Code Online (Sandbox Code Playgroud)

python openapi pydantic fastapi

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

是否可以将路径传递到 fastapi 端点?

我正在尝试使用 fastapi 创建一个遍历 api 的文件夹。假设我有这样的终点:

@root_router.get("/path/{path}")
def take_path(path):
    logger.info("test %s", path)
    return path
Run Code Online (Sandbox Code Playgroud)

如果我对浏览器执行并调用“URL:PORT/path/path”

它返回“路径”,很简单。但如果我尝试“URL:PORT/path/path/path”,代码甚至不会到达记录器。我认为这是有道理的,因为 API 不存在该端点。但它确实存在于我的服务器上。我已经想出了其他方法来做到这一点,即将路径作为参数数组传递,并用 / 分隔符在代码中重新构建,但是在 url 中传递参数感觉有点笨拙,如果我可以像下面一样移动 url 中的路径我的服务器,那将是理想的。这可行吗?

谢谢。

python python-3.x fastapi

3
推荐指数
1
解决办法
1159
查看次数

如何使用 FastAPI 和 Jinja2 模板提交 HTML 表单 <input> 值?

我在尝试将值从 HTML 表单<input>元素传递到表单的action属性并将其发送到 FastAPI 服务器时遇到以下问题。

这是 Jinja2 (HTML) 模板的加载方式:

# Test TEMPLATES
@app.get("/test",response_class=HTMLResponse)
async def read_item(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})
Run Code Online (Sandbox Code Playgroud)

我的 HTML 表单:

<form action="/disableSubCategory/{{subCatName}}">
    <label for="subCatName">SubCategory:</label><br>
    <input type="text" id="subCatName" name="subCatName" value=""><br>
    <input type="submit" value="Disable">
</form>
Run Code Online (Sandbox Code Playgroud)

我的 FastAPI 端点将在表单操作中调用:

<form action="/disableSubCategory/{{subCatName}}">
    <label for="subCatName">SubCategory:</label><br>
    <input type="text" id="subCatName" name="subCatName" value=""><br>
    <input type="submit" value="Disable">
</form>
Run Code Online (Sandbox Code Playgroud)

我得到的错误:

"GET /disableSubCategory/?subCatName=Barber HTTP/1.1" 404 Not Found
Run Code Online (Sandbox Code Playgroud)

我想要实现的是以下 FastAPI 调用:

/disableSubCategory/{subCatName} ==> "/disableSubCategory/Barber"
Run Code Online (Sandbox Code Playgroud)

谁能帮助我理解我做错了什么?

谢谢。狮子座

html python jinja2 fastapi

3
推荐指数
1
解决办法
9955
查看次数

如何将FastAPI请求转发到另一台服务器?

我有一个用于测试/开发目的的 FastAPI 应用程序。我想要的是,到达我的应用程序的任何请求都会按原样自动发送到另一台服务器上的另一个应用程序,并具有完全相同的参数和相同的端点。这不是重定向,因为我仍然希望应用程序像往常一样处理请求并返回值。我只想向不同服务器上的不同版本的应用程序发起类似的请求,而不需要等待其他服务器的答复,以便其他应用程序获取该请求,就像原始请求发送给它一样。

我怎样才能做到这一点?以下是我用于处理请求的示例代码:

@app.post("/my_endpoint/some_parameters")
def process_request(
    params: MyParamsClass,
    pwd: str = Depends(authenticate),
):
    # send the same request to http://my_other_url/my_endpoint/
    return_value = process_the_request(params)
    return return_value.as_json()
Run Code Online (Sandbox Code Playgroud)

python rest request forward fastapi

3
推荐指数
1
解决办法
5313
查看次数

如何在 FastAPI POST 请求中同时添加文件和 JSON 正文?

具体来说,我希望以下示例能够正常工作:

from typing import List
from pydantic import BaseModel
from fastapi import FastAPI, UploadFile, File


app = FastAPI()


class DataConfiguration(BaseModel):
    textColumnNames: List[str]
    idColumn: str


@app.post("/data")
async def data(dataConfiguration: DataConfiguration,
               csvFile: UploadFile = File(...)):
    pass
    # read requested id and text columns from csvFile
Run Code Online (Sandbox Code Playgroud)

如果这不是 POST 请求的正确方法,请告诉我如何从 FastAPI 中上传的 CSV 文件中选择所需的列。

python http http-post pydantic fastapi

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