无法处理的实体,使用 fastapi 发送 POST 请求?

huangapple go评论162阅读模式
英文:

Unprocessable entity with fastapi post request?

问题

我只会为你提供代码的翻译部分,以下是代码的翻译:

  1. 我只是尝试在业余时间使用fastapi我在我的POST请求中遇到了422无法处理的实体错误
  2. 我为我的产品创建了一个pydantic模型
  3. class post_products(BaseModel):
  4. id: int
  5. description: str
  6. price: int
  7. 然后创建了一个POST端点
  8. @app.post('/send/data', status_code=201)
  9. async def process_data(product: post_products):
  10. products_list.append(product)
  11. if product in products_list:
  12. return True
  13. 我相信这个函数的功能是它接受一个post_products实例将其添加到products_list然后如果添加成功则返回True然后我使用以下代码调用这个端点
  14. product = post_products(id=12, description='hello', price=93) # 创建一个类的实例
  15. product = product.model_dump() # 将这个实例转换为字典
  16. response = requests.post("http://127.0.0.1:8000/send/data", data=product)

请注意,代码中的注释和变量名没有翻译,保持原样。

英文:

I'm just having a go at using fastapi for hobbyiest purposes. I am getting the 422 unprocessable entity error with my post request

I've created a pydantic model for my products

  1. class post_products(BaseModel):
  2. id: int
  3. description: str
  4. price: int

Then have a post endpoint created

  1. @app.post('/send/data', status_code=201)
  2. async def process_data(product: post_products):
  3. products_list.append(product)
  4. if(product in products_list):
  5. return True

which i believe functions like, it takes in a post_products instance adds it to the products_list and then returns true if the add was successful, I then call this endPoint with

  1. product = post_products(id=12,description='hello', price=93) creates and instance of the class
  2. product = product.model_dump() makes this instance into a dictionary
  3. response = requests.post("http://127.0.0.1:8000/send/data", data= product)

Sorry Gordon i've updated it with the result. The product is a dict and its this

  1. {'id': 12, 'description': 'hello', 'price': 93}

答案1

得分: 0

你正在使用表单数据发送请求,而您的POST端点接受JSON。更改为

  1. response = requests.post("http://127.0.0.1:8000/send/data", json=product)

应该解决问题。

英文:

You're sending your request using form data, while your post endpoint accepts json. Changing to

  1. response = requests.post("http://127.0.0.1:8000/send/data", json=product)

should do the trick.

huangapple
  • 本文由 发表于 2023年8月11日 00:08:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76877536.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定