【AI】【Python】pydantic库学习demo

3 篇文章 0 订阅
本文介绍了Pydantic库在Python中的应用,重点讲解了数据类型定义、验证规则、必填校验和SchemaJson的使用。通过实例展示了如何创建模型、进行数据验证以及使用@validator装饰器进行字段验证。
摘要由CSDN通过智能技术生成

因为工作中学习AI,然后包括看源码,以及看代码都使用到了pydantic库,因此下面是一些最主要的20%,以学会其80%的精髓。

pydantic 库是 python 中用于数据接口定义检查与设置管理的库。
pydantic 在运行时强制执行类型提示,并在数据无效时提供友好的错误。

这个帖子比较全面:pydantic学习教程

必填校验和Schema Json


# 学习一些pydatic库的api

'''
用于数据验证和设置管理的Python库
它可以帮助我们定义数据类型,进行数据验证,以及自动
'''

from pydantic import BaseModel
from typing import List, Optional
from datetime import datetime

class User(BaseModel):
    id: int	# 必填
    name: str = 'John Doe' # 非必填
    signup_ts: Optional[datetime] = None
    friends: List[int] = []

def test_validation_error():

    from pydantic import ValidationError

    try:
        user = User(signup_ts='2022-01-01 12:00', friends=[1, '2', b'3'])
        print(user)
    except ValidationError as e:
        print(e) # error,报错id是必填的



def test_json_schema():
    from pydantic import BaseModel

    class User(BaseModel):
        id: int
        name: str = 'John Doe'
        signup_ts: Optional[datetime] = None
        friends: List[int] = []

    print(User.schema_json(indent=2)) # 返回json字符串,结构化的显示那些是必填的
    
    
if __name__ == "__main__":
    test_validation_error()
    test_json_schema()

@valiator的使用

# 继承了StringPromptTemplate和BaseModel
class FunctionExplainerPromptTemplate(StringPromptTemplate, BaseModel):
    """ A custom prompt template that takes in the function name as input, and formats the prompt template to provide the source code of the function. """

    @validator("input_variables")
    def validate_input_variables(cls, v):
        """ Validate that the input variables are correct. """
        if len(v) != 1 or "function_name" not in v:
            raise ValueError("function_name must be the only input_variable.")
        return v

# Generate a prompt for the function "get_source_code"
prompt = fn_explainer.format(function_name=get_source_code)
print(prompt)

@validator是pydantic库中的一个装饰器,用于对特定字段进行验证。当您在类中使用@validator时,它会将方法标记为验证器,并将其应用于指定的字段。

在这个例子中,validate_input_variables是一个验证器方法,它验证了输入变量的正确性。这个方法检查两个条件:

  1. 输入变量的数量是否为1。
  2. 输入变量中是否包含"function_name"。

如果这两个条件都不满足,那么就会抛出一个ValueError异常,表示"function_name"必须是唯一的输入变量。

结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值