关于fastapi请求的问题,请求post

Question about request of fastapi, request post

我使用 fastapi 构建我的网络服务器。

我需要知道客户端的 IP 地址,所以我遵循这个指南 https://fastapi.tiangolo.com/advanced/using-request-directly/

这是我的路由器功能

from fastapi import Request
...

@router.post("/login")
async def login(id: str, password: str, request: Request):

我的客户就是这样

import requests
...

response = requests.post(my_url, json={"id": id, "password": password})

但客户端收到此消息:

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

服务器给出此消息:

"POST /jobs/login HTTP/1.1" 422 Unprocessable Entity

所以我认为需要Request字段或者传输的数据格式不对..

有解决办法吗?

我想我发现了问题所在以及为什么会出现 422 无法处理的实体 错误

async def login(id: str, password: str, request: Request):

idpassword 是查询参数,但您试图传递 JSON 数据而不是查询参数。

response = requests.post(my_url, json={"id": id, "password": password})

如果你想让这段代码工作,你应该传递 idpassword 作为查询参数

import requests

my_url = "http://127.0.0.1:8000/login"
id = "1"
password = "hello"
params = {'id': id, 'password': password}
response = requests.post(my_url, params=params)

这是完整的代码。 main.py

from fastapi import Request, FastAPI
app = FastAPI()

@app.post("/login")
async def login(id: str, password: str, request: Request):
    ip = request.client.host
    return {
        "id":id,
        "password": password,
        "host": ip
    }


test.py

import requests

my_url = "http://127.0.0.1:8000/login"

id = "1"
password = "hello"

params = {'id': id, 'password': password}

response = requests.post(my_url, params=params)

如果您尚未定义 Pydantic 输入模式,则必须明确告诉 FastAPI 您想要从 JSON 正文中检索每个参数。

from fastapi import Request, FastAPI, APIRouter, Body

app = FastAPI()
router = APIRouter()


@router.post("/login")
async def login(request: Request, id: str = Body(...), password: str = Body(...)):
    print(id, password)
    

app.include_router(router)

要为登录请求定义模式,请创建一个继承自 BaseModel 的 Pydantic class:

from fastapi import Request, FastAPI, APIRouter, Body
from pydantic import BaseModel


class LoginSchema(BaseModel):
    id: str
    password: str


app = FastAPI()
router = APIRouter()


@router.post("/login-schema")
async def login(request: Request, login: LoginSchema):
    print(login.id, login.password)


app.include_router(router)