{"id":205270,"date":"2025-05-29T11:58:34","date_gmt":"2025-05-29T03:58:34","guid":{"rendered":"https:\/\/server.hk\/cnblog\/205270\/"},"modified":"2025-05-29T11:58:34","modified_gmt":"2025-05-29T03:58:34","slug":"pydantic%ef%bc%9a%e6%89%8b%e5%8a%a8%e9%aa%8c%e8%af%81%e7%9a%84%e7%bb%88%e7%bb%93%ef%bc%81","status":"publish","type":"post","link":"https:\/\/server.hk\/cnblog\/205270\/","title":{"rendered":"Pydantic\uff1a\u624b\u52a8\u9a8c\u8bc1\u7684\u7ec8\u7ed3\uff01"},"content":{"rendered":"<p><b><\/b>     <\/p>\n<h1>Pydantic\uff1a\u624b\u52a8\u9a8c\u8bc1\u7684\u7ec8\u7ed3\uff01 <\/h1>\n<p>\u4eca\u5929\u5c06\u7ed9\u5927\u5bb6\u5e26\u6765<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\">\u300aPydantic\uff1a\u624b\u52a8\u9a8c\u8bc1\u7684\u7ec8\u7ed3\uff01 \u300b<\/span>\uff0c\u611f\u5174\u8da3\u7684\u670b\u53cb\u8bf7\u7ee7\u7eed\u770b\u4e0b\u53bb\u5427\uff01\u4ee5\u4e0b\u5185\u5bb9\u5c06\u4f1a\u6d89\u53ca\u5230<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\"><\/span>\u7b49\u7b49\u77e5\u8bc6\u70b9\uff0c\u5982\u679c\u4f60\u662f\u6b63\u5728\u5b66\u4e60<span style=\"color: #FF6600;, Helvetica, Arial, sans-serif;font-size: 14px;background-color: #FFFFFF\">\u6587\u7ae0<\/span>\u6216\u8005\u5df2\u7ecf\u662f\u5927\u4f6c\u7ea7\u522b\u4e86\uff0c\u90fd\u975e\u5e38\u6b22\u8fce\u4e5f\u5e0c\u671b\u5927\u5bb6\u90fd\u80fd\u7ed9\u6211\u5efa\u8bae\u8bc4\u8bba\u54c8~\u5e0c\u671b\u80fd\u5e2e\u52a9\u5230\u5927\u5bb6\uff01<\/p>\n<p>pydantic \u662f\u4e00\u4e2a python \u6570\u636e\u9a8c\u8bc1\u548c\u8bbe\u7f6e\u7ba1\u7406\u5e93\u3002\u5b83\u4f7f\u7528 python \u7c7b\u578b\u63d0\u793a\u6765\u9a8c\u8bc1\u548c\u89e3\u6790\u6570\u636e\uff0c\u786e\u4fdd\u60a8\u7684\u4ee3\u7801\u80fd\u591f\u5904\u7406\u6b63\u786e\u7ed3\u6784\u5316\u548c\u7c7b\u578b\u5316\u7684\u6570\u636e\u3002\u901a\u8fc7\u5229\u7528 python \u7684\u7c7b\u4f3c\u6570\u636e\u7c7b\u7684\u6a21\u578b\u7ed3\u6784\uff0cpydantic \u53ef\u4ee5\u8f7b\u677e\u5b9a\u4e49\u590d\u6742\u6570\u636e\u7684\u6a21\u5f0f\uff0c\u5e76\u4ee5\u5e72\u51c0\u7684 python \u65b9\u5f0f\u81ea\u52a8\u9a8c\u8bc1\u548c\u5e8f\u5217\u5316\/\u53cd\u5e8f\u5217\u5316\u6570\u636e\u3002\u8ba9\u6211\u4eec\u6765\u63a2\u8ba8\u4e00\u4e0b\u4e3b\u8981\u529f\u80fd\uff1a<\/p>\n<p>\u4f7f\u7528 python \u7684\u7c7b\u578b\u63d0\u793a\u6839\u636e\u6a21\u5f0f\u81ea\u52a8\u9a8c\u8bc1\u8f93\u5165\u6570\u636e\u3002<\/p>\n<pre>from pydantic import basemodel, validationerror\n\nclass user(basemodel):\n    id: int\n    name: str\n    email: str\n\n# valid input\nuser = user(id=1, name=\"john doe\", email=\"john@example.com\")\nprint(user)\n\n# invalid input\ntry:\n    user = user(id=\"not-an-integer\", name=\"jane\", email=\"jane@example.com\")\nexcept validationerror as err:\n    print(err)\n<\/pre>\n<p>\u6bcf\u5f53\u4f60\u60f3\u5b9a\u4e49\u6570\u636e\u6a21\u578b\u65f6\uff0c\u8bf7\u4f7f\u7528 pydantic.basemodel\uff01<\/p>\n<p>pydantic \u63d0\u4f9b\u4e86\u5f3a\u5927\u7684\u5de5\u5177\uff0c\u4e0d\u4ec5\u53ef\u4ee5\u9a8c\u8bc1\u6570\u636e\u6a21\u578b\uff0c\u8fd8\u53ef\u4ee5\u9a8c\u8bc1<strong>\u51fd\u6570<\/strong>\u7684\u8f93\u5165\u548c\u8f93\u51fa\u3002\u8fd9\u662f\u4f7f\u7528 @validate_call \u88c5\u9970\u5668\u5b9e\u73b0\u7684\uff0c\u5141\u8bb8\u60a8\u5bf9\u51fd\u6570\u53c2\u6570\u548c\u8fd4\u56de\u503c\u5f3a\u5236\u6267\u884c\u4e25\u683c\u7684\u6570\u636e\u9a8c\u8bc1\u3002\u5982\u679c\u63d0\u4f9b\u7684\u53c2\u6570\u6216\u8fd4\u56de\u7c7b\u578b\u4e0e\u9884\u671f\u7c7b\u578b\u4e0d\u5339\u914d\uff0c\u5219\u4f1a\u5f15\u53d1 validationerror\u3002<\/p>\n<pre>from pydantic import validate_call\n\n@validate_call\ndef greet(name: str, age: int) -&gt; str:\n    return f\"hello {name}, you are {age} years old.\"\n\n# valid input\nprint(greet(\"alice\", 30))  # output: hello alice, you are 30 years old.\n\n# invalid input\ntry:\n    greet(\"bob\", \"not-a-number\")\nexcept exception as e:\n    print(e)\n<\/pre>\n<p>\u901a\u8fc7\u5728 @validate_call \u4e2d\u542f\u7528 validate_return \u6807\u5fd7\uff0cpydantic \u8fd8\u5c06\u6839\u636e\u5176\u5e26\u6ce8\u91ca\u7684\u8fd4\u56de\u7c7b\u578b\u9a8c\u8bc1\u51fd\u6570\u7684\u8fd4\u56de\u503c\u3002\u8fd9\u53ef\u786e\u4fdd\u51fd\u6570\u9075\u5faa\u9884\u671f\u7684\u8f93\u51fa\u6a21\u5f0f\u3002<\/p>\n<pre>from pydantic import validate_call\n\n@validate_call(validate_return=true)\ndef calculate_square(number: int) -&gt; int:\n    return number ** 2  # correct return type\n\n# valid input and return\nprint(calculate_square(4))  # output: 16\n\n# invalid return value\n@validate_call(validate_return=true)\ndef broken_square(number: int) -&gt; int:\n    return str(number ** 2)  # incorrect return type\n\ntry:\n    broken_square(4)\nexcept exception as e:\n    print(e)\n<\/pre>\n<p>pydantic \u53ef\u4ee5\u5c06\u590d\u6742\u7684\u5d4c\u5957\u7ed3\u6784\uff08\u5305\u62ec json \u6570\u636e\uff09\u89e3\u6790\u4e3a\u6a21\u578b\u5bf9\u8c61\u3002<\/p>\n<pre>from pydantic import basemodel\nfrom typing import list\n\nclass item(basemodel):\n    name: str\n    price: float\n\nclass order(basemodel):\n    items: list[item]\n    total: float\n\n# json-like data\ndata = {\n    \"items\": [\n        {\"name\": \"apple\", \"price\": 1.2},\n        {\"name\": \"banana\", \"price\": 0.8}\n    ],\n    \"total\": 2.0\n}\n\norder = order(**data) \nprint(order) # items=[item(name='apple', price=1.2), item(name='banana', price=0.8)] total=2.0\n<\/pre>\n<p>pydantic \u6a21\u578b\u53ef\u4ee5\u5e8f\u5217\u5316\u4e3a json \u6216\u5b57\u5178\u5e76\u91cd\u6784\u56de\u6765\u3002<\/p>\n<pre>from pydantic import basemodel\n\nclass user(basemodel):\n    id: int\n    name: str\n    email: str\n\n# create a model instance\nuser = user(id=1, name=\"alice\", email=\"alice@example.com\")\n\n# serialize to dictionary and json\nuser_dict = user.model_dump()\nuser_json = user.model_dump(mode='json')\n\nprint(\"dictionary:\", user_dict)\nprint(\"json:\", user_json)\n\n# deserialize back to the model\nnew_user = user.model_validate(user_json)\nprint(\"parsed user:\", new_user)\n<\/pre>\n<p>\u6570\u636e\u9a8c\u8bc1\u4e0d\u662f\u5f3a\u5236\u7c7b\u578b\u9a8c\u8bc1\u3002\u4f8b\u5982\uff0c\u5982\u679c\u60a8\u5b9a\u4e49\u4e00\u4e2a\u6a21\u578b\uff0c\u5176\u4e2d id\u3001due_date \u548c\u4f18\u5148\u7ea7\u5b57\u6bb5\u5206\u522b\u4e3a int\u3001bool \u548c datetime \u7c7b\u578b\uff0c\u5219\u53ef\u4ee5\u4f20\u9012\uff1a<\/p>\n<ul>\n<li>\u6570\u5b57\u5b57\u7b26\u4e32\u4f5c\u4e3aid <\/li>\n<li> <strong>iso-8601<\/strong>\u3001<strong>utc<\/strong> \u6216\u5176\u4ed6\u65e5\u671f\u683c\u5f0f\u7684\u5b57\u7b26\u4e32\u4f5c\u4e3a due_date <\/li>\n<li> &#8216;yes&#8217;\/&#8217;no&#8217;\u3001&#8217;on&#8217;\/&#8217;off&#8217;\u3001&#8217;true&#8217;\/&#8217;false&#8217;\u30011\/0 \u7b49\u4f5c\u4e3a\u4f18\u5148\u7ea7 <\/li>\n<\/ul>\n<pre>from sensei import apimodel\nfrom datetime import datetime\n\n\nclass task(apimodel):\n    id: int\n    due_date: datetime\n    priority: bool\n\n\ntask = task(due_date='2024-10-15t15:30:00', id=\"1\", priority=\"yes\")\nprint(task)\n<\/pre>\n<p>\u7ed3\u679c\u5c06\u662f<\/p>\n<pre>task(id=1, due_date=datetime.datetime(2024, 10, 15, 15, 30), priority=true)\n<\/pre>\n<p>\u60a8\u8fd8\u53ef\u4ee5\u4f7f\u7528\u9a8c\u8bc1\u5668\u5728\u6a21\u578b\u4e2d\u5b9a\u4e49\u81ea\u5b9a\u4e49\u9a8c\u8bc1\u903b\u8f91\u3002\u5b83\u4eec\u5141\u8bb8\u60a8\u5e94\u7528\u66f4\u590d\u6742\u7684\u9a8c\u8bc1\u89c4\u5219\uff0c\u8fd9\u4e9b\u89c4\u5219\u65e0\u6cd5\u4f7f\u7528\u5185\u7f6e\u7c7b\u578b\u6216\u5b57\u6bb5\u7ea6\u675f\u8f7b\u677e\u8868\u8fbe\u3002\u9a8c\u8bc1\u5668\u662f\u901a\u8fc7 field_validator \u88c5\u9970\u5668\u6216 field \u5bf9\u8c61\u5b9a\u4e49\u7684\u3002\u60a8\u53ef\u4ee5\u5c06\u4e00\u4e2a\u6216\u591a\u4e2a\u5b57\u6bb5\u540d\u79f0\u4f20\u9012\u7ed9 field_validator\uff0c\u4ee5\u786e\u5b9a\u54ea\u4e9b\u5b57\u6bb5\u5c06\u4f7f\u7528\u6b64\u9a8c\u8bc1\u5668\uff0c\u6216\u8005\u901a\u8fc7\u201c*\u201d\u4e3a\u6bcf\u4e2a\u5b57\u6bb5\u5e94\u7528\u9a8c\u8bc1\u5668\u3002<\/p>\n<pre>from typing import Any\nfrom pydantic import Field, field_validator, EmailStr, BaseModel\n\nclass User(BaseModel):\n    id: int\n    username: str = Field(pattern=r'^\\w+$')\n    email: EmailStr\n    age: int = Field(18, ge=14)\n    is_active: bool = True\n    roles: list[str]\n\n    # Define validator executed 'before' internal parsing\n    @field_validator('roles', mode='before')\n    def _validate_roles(cls, value: Any):\n        return value.split(',') if isinstance(value, str) else value\n\nuser = User(id=1, username='john', email='john@example.com', roles='student,singer')\nprint(user) # id=1 username='john' email='john@example.com' age=18 is_active=True roles=['student', 'singer']\n<\/pre>\n<p>\u6709\u5f88\u591a\u7531 pydantic \u652f\u6301\u7684\u5f00\u6e90\u9879\u76ee\u3002\u8ba9\u6211\u4eec\u63a2\u7d22\u5176\u4e2d\u6700\u597d\u7684\uff1a<\/p>\n<p>pydantic \u6700\u7a81\u51fa\u7684\u7528\u4f8b\u4e4b\u4e00\u662f fastapi\uff0c\u8fd9\u662f\u4e00\u4e2a\u4f7f\u7528 python \u6784\u5efa api \u7684\u73b0\u4ee3 web \u6846\u67b6\u3002 fastapi \u5e7f\u6cdb\u4f7f\u7528 pydantic \u6a21\u578b\u8fdb\u884c\u8bf7\u6c42\u6b63\u6587\u9a8c\u8bc1\u3001\u67e5\u8be2\u53c2\u6570\u548c\u54cd\u5e94\u6a21\u5f0f\u3002<\/p>\n<ul>\n<li>\u6765\u6e90\uff1ahttps:\/\/github.com\/fastapi\/fastapi <\/li>\n<li>\u6587\u6863\uff1ahttps:\/\/fastapi.tiangolo.com <\/li>\n<\/ul>\n<p><img decoding=\"async\" src=\"https:\/\/www.17golang.com\/uploads\/20241127\/173270993467470e2e87597.jpg\" class=\"aligncenter\"><\/p>\n<p><strong>fastapi<\/strong> \u662f\u4e3a\u6784\u5efa api \u800c\u8bbe\u8ba1\u7684\uff0c\u800c sensei \u5219\u662f\u4e3a\u5feb\u901f\u3001\u8f7b\u677e\u5730\u5305\u88c5\u8fd9\u4e9b api \u800c\u8bbe\u8ba1\u7684\u3002\u7531 sensei \u63d0\u4f9b\u652f\u6301\u7684 api \u5ba2\u6237\u7aef\u53ef\u786e\u4fdd\u7528\u6237\u83b7\u5f97\u76f8\u5173\u7684\u6570\u636e\u6a21\u578b\uff0c\u5e76\u4e14\u4e0d\u4f1a\u51fa\u73b0\u4ee4\u4eba\u56f0\u60d1\u7684\u9519\u8bef\u3002<\/p>\n<ul>\n<li>\u6765\u6e90\uff1ahttps:\/\/github.com\/crocofactory\/sensei <\/li>\n<li>\u6587\u6863\uff1ahttps:\/\/sensei.crocofactory.dev <\/li>\n<\/ul>\n<p><img decoding=\"async\" src=\"https:\/\/www.17golang.com\/uploads\/20241127\/173270993467470e2e8885f.jpg\" class=\"aligncenter\"><\/p>\n<p><strong>sqlmodel<\/strong> \u548c <strong>typer<\/strong> \u662f fastapi \u7684\u521b\u5efa\u8005 sebasti\u00e1n ram\u00edrez \u5f00\u53d1\u7684\u4e24\u4e2a\u51fa\u8272\u7684\u9879\u76ee\u3002 <\/p>\n<p><strong>sqlmodel<\/strong> \u662f\u4e00\u4e2a\u65e8\u5728\u7b80\u5316 python \u5e94\u7528\u7a0b\u5e8f\u4e2d\u7684\u6570\u636e\u5e93\u4ea4\u4e92\u7684\u5e93\u3002 <strong>sqlmodel<\/strong> \u6784\u5efa\u4e8e <strong>sqlalchemy<\/strong> \u548c <strong>pydantic<\/strong> \u4e4b\u4e0a\uff0c\u5c06 orm \u7684\u5f3a\u5927\u529f\u80fd\u4e0e\u6570\u636e\u9a8c\u8bc1\u548c\u5e8f\u5217\u5316\u7684\u4fbf\u5229\u6027\u7ed3\u5408\u5728\u4e00\u8d77\u3002<\/p>\n<ul>\n<li>\u6765\u6e90\uff1ahttps:\/\/github.com\/fastapi\/sqlmodel <\/li>\n<li>\u6587\u6863\uff1ahttps:\/\/sqlmodel.tiangolo.com <\/li>\n<\/ul>\n<p><strong>typer<\/strong> \u662f\u4e00\u4e2a\u4f7f\u7528 python \u521b\u5efa\u547d\u4ee4\u884c\u754c\u9762 (cli) \u5e94\u7528\u7a0b\u5e8f\u7684\u6846\u67b6\u3002\u5b83\u901a\u8fc7\u4f7f\u7528 python \u7684\u7c7b\u578b\u63d0\u793a\u81ea\u52a8\u751f\u6210\u7528\u6237\u53cb\u597d\u7684 cli \u547d\u4ee4\u548c\u5e2e\u52a9\u6587\u672c\u6765\u7b80\u5316\u6d41\u7a0b\u3002<\/p>\n<ul>\n<li>\u6765\u6e90\uff1ahttps:\/\/github.com\/fastapi\/typer <\/li>\n<li>\u6587\u6863\uff1ahttps:\/\/typer.tiangolo.com <\/li>\n<\/ul>\n<p>\u5230\u8fd9\u91cc\uff0c\u6211\u4eec\u4e5f\u5c31\u8bb2\u5b8c\u4e86\u300aPydantic\uff1a\u624b\u52a8\u9a8c\u8bc1\u7684\u7ec8\u7ed3\uff01 \u300b\u7684\u5185\u5bb9\u4e86\u3002\u4e2a\u4eba\u8ba4\u4e3a\uff0c\u57fa\u7840\u77e5\u8bc6\u7684\u5b66\u4e60\u548c\u5de9\u56fa\uff0c\u662f\u4e3a\u4e86\u66f4\u597d\u7684\u5c06\u5176\u8fd0\u7528\u5230\u9879\u76ee\u4e2d\uff0c\u6b22\u8fce\u5173\u6ce8\u516c\u4f17\u53f7\uff0c\u5e26\u4f60\u4e86\u89e3\u66f4\u591a\u5173\u4e8e\u7684\u77e5\u8bc6\u70b9\uff01<\/p>\n<p>      \u7248\u672c\u58f0\u660e \u672c\u6587\u8f6c\u8f7d\u4e8e\uff1adev.to \u5982\u6709\u4fb5\u72af\uff0c\u8bf7\u8054\u7cfb\u5220\u9664<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Pydantic\uff1a\u624b\u52a8\u9a8c\u8bc1\u7684\u7ec8\u7ed3&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4925],"tags":[],"class_list":["post-205270","post","type-post","status-publish","format-standard","hentry","category-4925"],"_links":{"self":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/205270","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/comments?post=205270"}],"version-history":[{"count":0,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/205270\/revisions"}],"wp:attachment":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/media?parent=205270"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/categories?post=205270"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/tags?post=205270"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}