💝💝💝欢迎来到我的博客,很高兴能够在这里和您见面!希望您在这里可以感受到一份轻松愉快的氛围,不仅可以获得有趣的内容和知识,也可以畅所欲言、分享您的想法和见解。

【Python系列】发送post请求_开发语言

  • 推荐:kwan 的首页,持续学习,不断总结,共同进步,活到老学到老
  • 导航
  • 檀越剑指大厂系列:全面总结 java 核心技术,jvm,并发编程 redis,kafka,Spring,微服务等
  • 常用开发工具系列:常用的开发工具,IDEA,Mac,Alfred,Git,typora 等
  • 数据库系列:详细总结了常用数据库 mysql 技术点,以及工作中遇到的 mysql 问题等
  • 新空间代码工作室:提供各种软件服务,承接各种毕业设计,毕业论文等
  • 懒人运维系列:总结好用的命令,解放双手不香吗?能用一个命令完成绝不用两个操作
  • 数据结构与算法系列:总结数据结构和算法,不同类型针对性训练,提升编程思维,剑指大厂

非常期待和您一起在这个小小的网络世界里共同探索、学习和成长。💝💝💝 ✨✨ 欢迎订阅本专栏 ✨✨


博客目录
  • 一.post 请求
  • 1. 定义数据模型
  • 2. 创建 API 路由
  • 3. 处理数组数据
  • 4. 启动和测试 API
  • 5. 异常处理
  • 二.实现步骤
  • 1.客户端
  • 2.请求参数
  • 3.服务端
  • 4.总结


一.post 请求

FastAPI 是一个现代、快速(高性能)的 Web 框架,用于构建 API,它基于 Python 3.6+ 类型提示。FastAPI 支持使用 Pydantic 进行数据验证,这意味着你可以定义请求和响应的数据模型,FastAPI 会自动为你生成请求的验证和响应的序列化。

在 FastAPI 中,处理数组参数的 POST 请求是一个常见的需求,尤其是在需要接收大量数据或批量操作的场景中。下面我们将详细探讨如何使用 FastAPI 来实现这一功能。

【Python系列】发送post请求_python_02

1. 定义数据模型

首先,我们需要定义一个数据模型来表示 POST 请求中的数组参数。这可以通过 Pydantic 模型来实现。

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: str = None

class ItemsList(BaseModel):
    items: List[Item]
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

在这个例子中,Item 是一个基本的数据模型,包含 namedescription 两个字段。ItemsList 模型包含一个 items 字段,它是一个 Item 类型的列表。

2. 创建 API 路由

接下来,我们需要创建一个 API 路由来处理 POST 请求。在 FastAPI 中,你可以使用 @app.post 装饰器来定义一个 POST 路由。

from fastapi import FastAPI, HTTPException
from typing import List

app = FastAPI()

@app.post("/items/")
async def create_items(items_list: ItemsList):
    items = items_list.items
    # 这里可以添加逻辑来处理接收到的数组数据
    return {"message": "Items received", "items": items}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

在这个例子中,我们定义了一个 /items/ 路由,它接收一个 ItemsList 类型的请求体。create_items 函数将异步处理请求,并返回接收到的数组数据。

3. 处理数组数据

create_items 函数中,你可以添加任何你需要的逻辑来处理数组数据。例如,你可能需要将这些数据存储到数据库中,或者进行一些计算和验证。

4. 启动和测试 API

一旦你定义了路由和数据模型,你可以启动 FastAPI 应用并使用工具如 Postman 或 curl 来测试你的 API。

uvicorn main:app --reload
  • 1.

使用 curl 测试 POST 请求:

curl -X 'POST' \
  'http://127.0.0.1:8000/items/' \
  -H 'accept: application/json' \
  -H 'Content-Type: application/json' \
  -d '{
  "items": [
    {
      "name": "Item 1",
      "description": "Description of Item 1"
    },
    {
      "name": "Item 2"
    }
  ]
}'
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
5. 异常处理

在处理 POST 请求时,异常处理是非常重要的。FastAPI 允许你使用 HTTPException 来抛出自定义的异常。

@app.post("/items/")
async def create_items(items_list: ItemsList):
    try:
        items = items_list.items
        # 模拟异常情况
        raise ValueError("An error occurred")
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    return {"message": "Items received", "items": items}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

【Python系列】发送post请求_python_03

二.实现步骤

1.客户端
def voc_list(app_id: str, words: List[str]):
    try:
        # 指定请求参数
        url: str = f"{api_base}/voc/list"
        data = {
            "app_id": app_id,
            "words": words
        }
        headers = {
            'accept': 'application/json',
            'Content-Type': 'application/json'
        }
        response = requests.post(url, data=json.dumps(data), headers=headers)
        # 检查响应状态码
        if response.status_code == 200:
            # 请求成功
            logger.info(f'voc list ok.:{response}')
            return response.text
        else:
            # 请求失败
            logger.error(f'voc list fail:{response}')
    except Exception as e:
        logger.error(f'voc list exception:{e}')
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
2.请求参数
class VocListRequest(BaseModel):
    app_id: str
    words: List[str]
  • 1.
  • 2.
  • 3.
3.服务端
@staticmethod
@AppRouter.post("/voc/list", summary="查询", description="查询")
async def voc_list(voc_list: VocListRequest):
   app_id = voc_list.app_id
   words = voc_list.words
   app = await AppManager().get_app_info(app_id)
   res = {}
   if app:
      vocab_table_ids = app.vocab_table_info
      if vocab_table_ids and len(vocab_table_ids) > 0:
            db = get_sqlalchemy_db
            with db.get_session() as session:
               vocabs = session.query(AlchemyVocab).filter(
                  AlchemyVocab.vocab_table_id.in_(vocab_table_ids)).filter(
                  AlchemyVocab.name.in_(words)).all()
               res = {vocab.name: vocab.desc for vocab in vocabs if vocab.desc is not None}
   return {
      "code": 0,
      "msg": "成功",
      "data": res
   }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
4.总结

FastAPI 提供了一个强大而灵活的方式来处理数组参数的 POST 请求。通过定义 Pydantic 模型,你可以确保数据的验证和序列化是自动化的。使用 FastAPI 的路由和异常处理功能,你可以构建一个健壯且易于维护的 API。

FastAPI 的性能和易用性使其成为构建 API 的首选框架之一,特别是当你需要处理复杂的数据结构和大量的数据时。通过上述步骤,你可以快速地实现一个能够接收和处理数组参数的 POST 请求的 API。

请注意,本文只是一个概述,实际开发中可能需要考虑更多的因素,如安全性、认证、日志记录等。但 FastAPI 提供了丰富的功能和中间件来支持这些高级特性。

觉得有用的话点个赞 👍🏻 呗。
❤️❤️❤️本人水平有限,如有纰漏,欢迎各位大佬评论批评指正!😄😄😄

💘💘💘如果觉得这篇文对你有帮助的话,也请给个点赞、收藏下吧,非常感谢!👍 👍 👍

🔥🔥🔥Stay Hungry Stay Foolish 道阻且长,行则将至,让我们一起加油吧!🌙🌙🌙

【Python系列】发送post请求_python_04