FastAPI从入门到实战(7)——请求体函数的参数设置

系统管理员 2024-03-31 12:29 211阅读 0赞

上一篇记录了FastAPI中声明请求体的相关内容,本文记录一下零碎的函数特性和参数特性相关内容。

Pydantic schema_extra

可以使用 Configschema_extra 为Pydantic模型声明一个示例:

  1. class City(BaseModel):
  2. country:str = "中国"
  3. provence:str = Field(...,example = "四川") # Field可以定义请求体的格式和类型
  4. citys: Optional[List] = None
  5. population: int = Field(default=None,title="人口数",ge=1000)
  6. class Config:
  7. schema_extra = {
  8. "example":{
  9. "country":"中国",
  10. "provence":"四川",
  11. "citys":["绵阳","成都","遂宁","..."],
  12. "population":66666666
  13. }
  14. }

image-20221125215909375

Field参数设置

fieldPathQueryBody可以设置default、title等信息;具体参看源码;

  1. def Field(
  2. default: Any = Undefined,
  3. *,
  4. default_factory: Optional[NoArgAnyCallable] = None,
  5. alias: str = None,
  6. title: str = None,
  7. description: str = None,
  8. exclude: Union['AbstractSetIntStr', 'MappingIntStrAny', Any] = None,
  9. include: Union['AbstractSetIntStr', 'MappingIntStrAny', Any] = None,
  10. const: bool = None,
  11. gt: float = None,
  12. ge: float = None,
  13. lt: float = None,
  14. le: float = None,
  15. multiple_of: float = None,
  16. allow_inf_nan: bool = None,
  17. max_digits: int = None,
  18. decimal_places: int = None,
  19. min_items: int = None,
  20. max_items: int = None,
  21. unique_items: bool = None,
  22. min_length: int = None,
  23. max_length: int = None,
  24. allow_mutation: bool = True,
  25. regex: str = None,
  26. discriminator: str = None,
  27. repr: bool = True,
  28. **extra: Any,
  29. )

Body参数设置

BodyPathQuery是一个性质的,分别声明请求体、路径参数、查询参数

  1. # 无 Body 额外参数
  2. @app04.post("/stu04/notbodyfield")
  3. def stu04_not_bdy_field(
  4. param:Dog
  5. ):
  6. return param
  7. # Body 额外参数
  8. @app04.post("/stu04/bodyfield")
  9. def stu04_bdy_field(
  10. param:Dog = Body(
  11. example={
  12. "name":"小七",
  13. "age":15,
  14. "varieties":"泰迪",
  15. "birthday":date.today()
  16. }
  17. )
  18. ):
  19. return param

image-20221125220527054

image-20221125220553476

其他数据类型

目前用的都是常见的数据类型,包括int、float、str、bool等等;

也可以使用其他数据类型,几乎所有Pydantic支持的数据类型都可以:Pydantic-字段类型

也可以参看源码:

  1. __all__ = [
  2. # annotated types utils
  3. 'create_model_from_namedtuple',
  4. 'create_model_from_typeddict',
  5. # dataclasses
  6. 'dataclasses',
  7. # class_validators
  8. 'root_validator',
  9. 'validator',
  10. # config
  11. 'BaseConfig',
  12. 'ConfigDict',
  13. 'Extra',
  14. # decorator
  15. 'validate_arguments',
  16. # env_settings
  17. 'BaseSettings',
  18. # error_wrappers
  19. 'ValidationError',
  20. # fields
  21. 'Field',
  22. 'Required',
  23. # main
  24. 'BaseModel',
  25. 'create_model',
  26. 'validate_model',
  27. # network
  28. 'AnyUrl',
  29. 'AnyHttpUrl',
  30. 'FileUrl',
  31. 'HttpUrl',
  32. 'stricturl',
  33. 'EmailStr',
  34. 'NameEmail',
  35. 'IPvAnyAddress',
  36. 'IPvAnyInterface',
  37. 'IPvAnyNetwork',
  38. 'PostgresDsn',
  39. 'CockroachDsn',
  40. 'AmqpDsn',
  41. 'RedisDsn',
  42. 'MongoDsn',
  43. 'KafkaDsn',
  44. 'validate_email',
  45. # parse
  46. 'Protocol',
  47. # tools
  48. 'parse_file_as',
  49. 'parse_obj_as',
  50. 'parse_raw_as',
  51. 'schema_of',
  52. 'schema_json_of',
  53. # types
  54. 'NoneStr',
  55. 'NoneBytes',
  56. 'StrBytes',
  57. 'NoneStrBytes',
  58. 'StrictStr',
  59. 'ConstrainedBytes',
  60. 'conbytes',
  61. 'ConstrainedList',
  62. 'conlist',
  63. 'ConstrainedSet',
  64. 'conset',
  65. 'ConstrainedFrozenSet',
  66. 'confrozenset',
  67. 'ConstrainedStr',
  68. 'constr',
  69. 'PyObject',
  70. 'ConstrainedInt',
  71. 'conint',
  72. 'PositiveInt',
  73. 'NegativeInt',
  74. 'NonNegativeInt',
  75. 'NonPositiveInt',
  76. 'ConstrainedFloat',
  77. 'confloat',
  78. 'PositiveFloat',
  79. 'NegativeFloat',
  80. 'NonNegativeFloat',
  81. 'NonPositiveFloat',
  82. 'FiniteFloat',
  83. 'ConstrainedDecimal',
  84. 'condecimal',
  85. 'ConstrainedDate',
  86. 'condate',
  87. 'UUID1',
  88. 'UUID3',
  89. 'UUID4',
  90. 'UUID5',
  91. 'FilePath',
  92. 'DirectoryPath',
  93. 'Json',
  94. 'JsonWrapper',
  95. 'SecretField',
  96. 'SecretStr',
  97. 'SecretBytes',
  98. 'StrictBool',
  99. 'StrictBytes',
  100. 'StrictInt',
  101. 'StrictFloat',
  102. 'PaymentCardNumber',
  103. 'PrivateAttr',
  104. 'ByteSize',
  105. 'PastDate',
  106. 'FutureDate',
  107. # version
  108. 'compiled',
  109. 'VERSION',
  110. ]

源码

  1. # -*- coding: utf-8 -*-
  2. # @Time: 2022/11/25 21:21
  3. # @Author: MinChess
  4. # @File: stu04.py
  5. # @Software: PyCharm
  6. from fastapi import APIRouter,Body
  7. from pydantic import BaseModel,Field
  8. from typing import Optional,List
  9. from datetime import date
  10. app04 = APIRouter()
  11. # 创建一个数据模型
  12. class City(BaseModel):
  13. country:str = "中国"
  14. provence:str = Field(...,example = "四川") # Field可以定义请求体的格式和类型
  15. citys: Optional[List] = None
  16. population: int = Field(default=None,title="人口数",ge=1000)
  17. class Config:
  18. schema_extra = {
  19. "example":{
  20. "country":"中国",
  21. "provence":"四川",
  22. "citys":["绵阳","成都","遂宁","..."],
  23. "population":66666666
  24. }
  25. }
  26. # Pydantic schema_extra
  27. @app04.post("/stu04/schemaextra")
  28. def stu04_schema_extra(
  29. city:City
  30. ):
  31. return city
  32. # Field 的附加参数
  33. class Dog(BaseModel):
  34. name:str = Field(example = "小黑")
  35. age:int = Field(...,description="狗的年龄",gt=0,le=20)
  36. varieties:str = Field(default="拉布拉多",title="狗的品种")
  37. birthday:date
  38. # 无 Body 额外参数
  39. @app04.post("/stu04/notbodyfield")
  40. def stu04_not_bdy_field(
  41. param:Dog
  42. ):
  43. return param
  44. # Body 额外参数
  45. @app04.post("/stu04/bodyfield")
  46. def stu04_bdy_field(
  47. param:Dog = Body(
  48. example={
  49. "name":"小七",
  50. "age":15,
  51. "varieties":"泰迪",
  52. "birthday":date.today()
  53. }
  54. )
  55. ):
  56. return param

30b7b3ba49344b6691969078c7df196e.png欢 迎 关 注 博 主 个 人 小 程 序!

发表评论

表情:
评论列表 (有 0 条评论,211人围观)

还没有评论,来说两句吧...

相关阅读