后端(fastAPI)学习笔记(CLASS 1):扩展基础

一、python的类型声明

1、类型声明的背景和作用

python 3.6+ 版本引入了"类型提示"

1、类型提示是一种新的语法,用来声明变量的类型

2、提高编译器和工具的支持能力

为什么要学习类型提示

1、了解类型提示不仅仅对使用FastAPI有帮助,也能提高代码的可读性度和可靠性有很大的帮助

类型提示的好处

1、不改变原始运行结果

2、提供更好的编译器支持和代码补全

编译器支持

1、通过类型提示,编译器可以帮助检查代码中的错误

2、例如,将int类型的age转换为str类型

以下是类型声明语法的示例代码:

python 复制代码
# python中类型声明

# 变量类型的声明
a: int = 20
b: str = '11,22'
c: list = [11, 22]
print(a)

# 函数的参数和返回值的类型声明
def work(a: int, b: int) -> int:
    return a+b

# 若不是int类型则会报错
print(work(1, 1))
2、使用场景案例

1、变量的类型声明

python 复制代码
name: str = '张三'
age: int = 18

2、函数参数的类型声明

python 复制代码
def work(a: int, b: int):
    return a+b

3、函数返回值的类型声明

python 复制代码
def work2(name: str, age: int) -> dict:
    return { "名字": name, "年龄": int }

def work3(datas: list) -> dict:
    return dict(enumerate(datas))
3**、复合类型的类型声明**

上面的案例只对datas这个参数做了类型声明,对于datas中的数据并没有进行任何声明,那么这种复合类型的数据类型如何进行声明呢?需要使用typing标准库声明容器数据结构的类型和子类型

python 复制代码
# 比如 我希望datas是列表嵌套字典的数据格式:[{"name":"张三"}, {"age": 18}, {"addr":"地址"}]

from typing import List, Union

def work4(datas: List[dict]) -> dict:
    print(datas)
    return {"data": datas}

work4([{"name":"张三"}, {"age": 18}])

def work5(datas: List[Union[str, int]]) -> dict:
    print(datas)
    return {"data": datas}

work5(['名字', 18])
4、使用自定义类型声明
python 复制代码
class Person:
    def __init__(self, name: str, age: int):
        self.name = name
        self.age = age
        
def get_person_info(p: Person) -> dict:
    return {"名字": p.name, "年龄": p.age}

p = Person("张三", 18)
print(get_person_info(p))

二、Pydantic模型

1、使用方法
python 复制代码
# fastapi关于类型校验的参数模块pydantic----中的pydantic-core专门负责校验类型
# pip install fastapi

from pydantic import BaseModel, ValidationError 

class Student(BaseModel):
    name: str
    age: int
    sex: str
    
def work(stu: Student):
    print(stu.name)
    print(stu.age)
    print(stu.sex)
    
if __name__ == '__main__':
    try:
        s = Student(name="张三", age=[18], sex="男")
    except ValidationError as e:
        print(e.json())

此时抛出的错误为:

PS D:\py> & c:/Users/judge/myenv/Scripts/python.exe d:/py/study-1.py

{"type":"int_type","loc":\["age"\],"msg":"Input should be a valid integer","input":\[18\],"url":"https://errors.pydantic.dev/2.11/v/int_type"}

2、pydantic模型对象的常用操作
python 复制代码
# 1、转换为字典
print(p.dict())
# 2、获取部分字段
res = p.dict(include={'name', 'age'})
print(type(res), res)

# 3、进行序列化---->json字符串
print(p.json())
# 4、进行反序列化---->对象 exclude
res2 = p.json(include={'name', 'age'})
print(type(res2), res2)
相关推荐
d111111111d12 小时前
什么是内存对齐?在STM32上面如何通过编辑器指令来实现内存对齐。
笔记·stm32·单片机·嵌入式硬件·学习·编辑器
蒙奇D索大13 小时前
【数据结构】考研408 | 伪随机探测与双重散列精讲:散列的艺术与均衡之道
数据结构·笔记·学习·考研
舞动青春8813 小时前
Ubuntu安装QEMU过程及问题记录
linux·学习·ubuntu
知识分享小能手13 小时前
Ubuntu入门学习教程,从入门到精通,Ubuntu 22.04的基本配置 (3)
linux·学习·ubuntu
黑客思维者13 小时前
机器学习012:监督学习【回归算法】(对比)-- AI预测世界的“瑞士军刀”
人工智能·学习·机器学习·回归·逻辑回归
我想我不够好。13 小时前
实操练习 12.20
学习
Crkylin13 小时前
尚硅谷Linux应用层学习笔记(一)GCC编译
linux·笔记·学习
车载测试工程师13 小时前
CAPL学习-AVB交互层-功能函数-监听器函数函数
网络·学习·tcp/ip·capl·canoe
andwhataboutit?14 小时前
pytorch-CycleGAN-and-pix2pix学习
人工智能·pytorch·学习
vv_50114 小时前
大模型 langchain-组件学习(中)
人工智能·学习·langchain·大模型