FastAPI get请求 之路径参数,查询参数验证


引用博文: https://blog.csdn.net/wgPython/article/details/107525950

FastAPI之get请求

"""
本模块用来测试 FastApi 中 get和post请求参数:
         path: 路径参数
         ?: 查询参数
 以及 数据的校验,和异常处理
"""

from fastapi import FastAPI, Query, Path, Request
from typing import Optional
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse

# get请求参数的两种方式
# 方式一: 通过路径参数传参
app = FastAPI()  # 通过FastApi类实例化一个app对象


@app.get('/items/{item_id}')
async def read_item_id(item_id: int):
    """
    接受前端通过 路径参数(写在路径里的) 传递的id值 并返回前端
    :param item_id: 前端通过路径传递的id值
    :return: 前端传递的id值
    """
    return {'item_id': item_id}


@app.get('/bar')
async def read_bar(name: str, age: int):

    """
    接受通过 查询参数 传递的值 并返回
    :param name: 名字
    :param age: 年龄
    :return: 名字和年龄
    """

    return {'name': name, 'age': age}


# 自定义request异常处理
@app.exception_handler(RequestValidationError)
async def request_validation_exception_handler(request: Request, exc: RequestValidationError):

    """
    通过重写 RequestValidationError类的 exception_handler方法 来自定义异常
    :param request: Request类的实例化对象
    :param exc: RequestValidationError的实例化对象
    :return: 400 用户发送的请求错误,服务器没有操作 msg: 错误的堆栈处理
    """

    print(f'参数不对{request.method},{request.url}')
    return JSONResponse({'code': 400, 'message': exc.errors()})


# 路径参数和查询参数验证的区别 路径参数验证使用path,查询参数验证使用query
# 路径参数验证
@app.get('/bar/{bar_id}')
async def read_foo(
        bar_id: int = Path(1, title='描述'),
        age: int = Query(..., le=120, title='年龄'),
        name: Optional[str] = Query(None, min_length=3, max_length=5, regex='^dong')
):

    """
    合法请求:
    http://127.0.0.1:8000/bar/10?age=10 name没有值
    http://127.0.0.1:8000/bar/10?age=10&name=dong
    路径参数: bar_id, 函数参数:bar_id, age, name
    :param bar_id: 路径参数 bar_id
    :param age: 年龄
    :param name: 姓名
    :return:
    """

    return {'bar_id': bar_id, 'age': age, 'name': name}


# get请求 查询参数验证
@app.get('/get_search_args')
async def get_search_args_test(
        search_id: int = Query(..., title='搜索ID'),
        name: Optional[str] = Query(..., title='姓名', min_length=3, max_length=5, regex='^dong'),
        age: Optional[int] = Query(None, title='年龄', le=100)
):

    """
    get请求查询参数测试函数 参数 search_id: 查找ID, name: '姓名', age: '年龄',三个参数为必填项
    :param search_id: 查询ID
    :param name: 查询姓名
    :param age:  查询年龄
    :return: search_id, name, age
    """

    return {'search_id': search_id, 'name': name, 'age': age}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM