Update python-fastapi generator to support Pydantic v2 (#17369)

* update python fastapi to support pydantic v2

* add new files

* update samples

* update samples

* update starlette

* update typing extensions

* update email validator
This commit is contained in:
William Cheng
2024-02-15 14:15:51 +08:00
committed by GitHub
parent 8cd34ac963
commit 887b860007
19 changed files with 1525 additions and 214 deletions

View File

@@ -6,8 +6,10 @@
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
"""
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
from fastapi import FastAPI

View File

@@ -1,28 +1,94 @@
# coding: utf-8
from __future__ import annotations
from datetime import date, datetime # noqa: F401
"""
OpenAPI Petstore
import re # noqa: F401
from typing import Any, Dict, List, Optional # noqa: F401
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
from pydantic import AnyUrl, BaseModel, EmailStr, Field, validator # noqa: F401
class ApiResponse(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
ApiResponse - a model defined in OpenAPI
code: The code of this ApiResponse [Optional].
type: The type of this ApiResponse [Optional].
message: The message of this ApiResponse [Optional].
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
try:
from typing import Self
except ImportError:
from typing_extensions import Self
class ApiResponse(BaseModel):
"""
Describes the result of uploading an image resource
""" # noqa: E501
code: Optional[StrictInt] = None
type: Optional[StrictStr] = None
message: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["code", "type", "message"]
model_config = {
"populate_by_name": True,
"validate_assignment": True,
"protected_namespaces": (),
}
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Self:
"""Create an instance of ApiResponse from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
_dict = self.model_dump(
by_alias=True,
exclude={
},
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Dict) -> Self:
"""Create an instance of ApiResponse from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"code": obj.get("code"),
"type": obj.get("type"),
"message": obj.get("message")
})
return _obj
code: Optional[int] = Field(alias="code", default=None)
type: Optional[str] = Field(alias="type", default=None)
message: Optional[str] = Field(alias="message", default=None)
ApiResponse.update_forward_refs()

View File

@@ -1,31 +1,103 @@
# coding: utf-8
from __future__ import annotations
from datetime import date, datetime # noqa: F401
"""
OpenAPI Petstore
import re # noqa: F401
from typing import Any, Dict, List, Optional # noqa: F401
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
from pydantic import AnyUrl, BaseModel, EmailStr, Field, validator # noqa: F401
class Category(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
Category - a model defined in OpenAPI
id: The id of this Category [Optional].
name: The name of this Category [Optional].
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, Field, StrictInt, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
try:
from typing import Self
except ImportError:
from typing_extensions import Self
class Category(BaseModel):
"""
A category for a pet
""" # noqa: E501
id: Optional[StrictInt] = None
name: Optional[Annotated[str, Field(strict=True)]] = None
__properties: ClassVar[List[str]] = ["id", "name"]
id: Optional[int] = Field(alias="id", default=None)
name: Optional[str] = Field(alias="name", default=None)
@field_validator('name')
def name_validate_regular_expression(cls, value):
"""Validates the regular expression"""
if value is None:
return value
@validator("name")
def name_pattern(cls, value):
assert value is not None and re.match(r"/^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$/", value)
if not re.match(r"^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$", value):
raise ValueError(r"must validate the regular expression /^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$/")
return value
Category.update_forward_refs()
model_config = {
"populate_by_name": True,
"validate_assignment": True,
"protected_namespaces": (),
}
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Self:
"""Create an instance of Category from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
_dict = self.model_dump(
by_alias=True,
exclude={
},
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Dict) -> Self:
"""Create an instance of Category from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"name": obj.get("name")
})
return _obj

View File

@@ -1,34 +1,111 @@
# coding: utf-8
from __future__ import annotations
from datetime import date, datetime # noqa: F401
"""
OpenAPI Petstore
import re # noqa: F401
from typing import Any, Dict, List, Optional # noqa: F401
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
from pydantic import AnyUrl, BaseModel, EmailStr, Field, validator # noqa: F401
class Order(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
Order - a model defined in OpenAPI
id: The id of this Order [Optional].
pet_id: The pet_id of this Order [Optional].
quantity: The quantity of this Order [Optional].
ship_date: The ship_date of this Order [Optional].
status: The status of this Order [Optional].
complete: The complete of this Order [Optional].
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from datetime import datetime
from pydantic import BaseModel, Field, StrictBool, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
try:
from typing import Self
except ImportError:
from typing_extensions import Self
class Order(BaseModel):
"""
An order for a pets from the pet store
""" # noqa: E501
id: Optional[StrictInt] = None
pet_id: Optional[StrictInt] = Field(default=None, alias="petId")
quantity: Optional[StrictInt] = None
ship_date: Optional[datetime] = Field(default=None, alias="shipDate")
status: Optional[StrictStr] = Field(default=None, description="Order Status")
complete: Optional[StrictBool] = False
__properties: ClassVar[List[str]] = ["id", "petId", "quantity", "shipDate", "status", "complete"]
@field_validator('status')
def status_validate_enum(cls, value):
"""Validates the enum"""
if value is None:
return value
if value not in ('placed', 'approved', 'delivered'):
raise ValueError("must be one of enum values ('placed', 'approved', 'delivered')")
return value
model_config = {
"populate_by_name": True,
"validate_assignment": True,
"protected_namespaces": (),
}
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Self:
"""Create an instance of Order from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
_dict = self.model_dump(
by_alias=True,
exclude={
},
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Dict) -> Self:
"""Create an instance of Order from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"petId": obj.get("petId"),
"quantity": obj.get("quantity"),
"shipDate": obj.get("shipDate"),
"status": obj.get("status"),
"complete": obj.get("complete") if obj.get("complete") is not None else False
})
return _obj
id: Optional[int] = Field(alias="id", default=None)
pet_id: Optional[int] = Field(alias="petId", default=None)
quantity: Optional[int] = Field(alias="quantity", default=None)
ship_date: Optional[datetime] = Field(alias="shipDate", default=None)
status: Optional[str] = Field(alias="status", default=None)
complete: Optional[bool] = Field(alias="complete", default=None)
Order.update_forward_refs()

View File

@@ -1,36 +1,122 @@
# coding: utf-8
from __future__ import annotations
from datetime import date, datetime # noqa: F401
"""
OpenAPI Petstore
import re # noqa: F401
from typing import Any, Dict, List, Optional # noqa: F401
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
from pydantic import AnyUrl, BaseModel, EmailStr, Field, validator # noqa: F401
from openapi_server.models.category import Category
from openapi_server.models.tag import Tag
class Pet(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
Pet - a model defined in OpenAPI
id: The id of this Pet [Optional].
category: The category of this Pet [Optional].
name: The name of this Pet.
photo_urls: The photo_urls of this Pet.
tags: The tags of this Pet [Optional].
status: The status of this Pet [Optional].
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, Field, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from openapi_server.models.category import Category
from openapi_server.models.tag import Tag
try:
from typing import Self
except ImportError:
from typing_extensions import Self
class Pet(BaseModel):
"""
A pet for sale in the pet store
""" # noqa: E501
id: Optional[StrictInt] = None
category: Optional[Category] = None
name: StrictStr
photo_urls: List[StrictStr] = Field(alias="photoUrls")
tags: Optional[List[Tag]] = None
status: Optional[StrictStr] = Field(default=None, description="pet status in the store")
__properties: ClassVar[List[str]] = ["id", "category", "name", "photoUrls", "tags", "status"]
@field_validator('status')
def status_validate_enum(cls, value):
"""Validates the enum"""
if value is None:
return value
if value not in ('available', 'pending', 'sold'):
raise ValueError("must be one of enum values ('available', 'pending', 'sold')")
return value
model_config = {
"populate_by_name": True,
"validate_assignment": True,
"protected_namespaces": (),
}
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Self:
"""Create an instance of Pet from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
_dict = self.model_dump(
by_alias=True,
exclude={
},
exclude_none=True,
)
# override the default output from pydantic by calling `to_dict()` of category
if self.category:
_dict['category'] = self.category.to_dict()
# override the default output from pydantic by calling `to_dict()` of each item in tags (list)
_items = []
if self.tags:
for _item in self.tags:
if _item:
_items.append(_item.to_dict())
_dict['tags'] = _items
return _dict
@classmethod
def from_dict(cls, obj: Dict) -> Self:
"""Create an instance of Pet from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"category": Category.from_dict(obj.get("category")) if obj.get("category") is not None else None,
"name": obj.get("name"),
"photoUrls": obj.get("photoUrls"),
"tags": [Tag.from_dict(_item) for _item in obj.get("tags")] if obj.get("tags") is not None else None,
"status": obj.get("status")
})
return _obj
id: Optional[int] = Field(alias="id", default=None)
category: Optional[Category] = Field(alias="category", default=None)
name: str = Field(alias="name")
photo_urls: List[str] = Field(alias="photoUrls")
tags: Optional[List[Tag]] = Field(alias="tags", default=None)
status: Optional[str] = Field(alias="status", default=None)
Pet.update_forward_refs()

View File

@@ -1,26 +1,92 @@
# coding: utf-8
from __future__ import annotations
from datetime import date, datetime # noqa: F401
"""
OpenAPI Petstore
import re # noqa: F401
from typing import Any, Dict, List, Optional # noqa: F401
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
from pydantic import AnyUrl, BaseModel, EmailStr, Field, validator # noqa: F401
class Tag(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
Tag - a model defined in OpenAPI
id: The id of this Tag [Optional].
name: The name of this Tag [Optional].
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
try:
from typing import Self
except ImportError:
from typing_extensions import Self
class Tag(BaseModel):
"""
A tag for a pet
""" # noqa: E501
id: Optional[StrictInt] = None
name: Optional[StrictStr] = None
__properties: ClassVar[List[str]] = ["id", "name"]
model_config = {
"populate_by_name": True,
"validate_assignment": True,
"protected_namespaces": (),
}
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Self:
"""Create an instance of Tag from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
_dict = self.model_dump(
by_alias=True,
exclude={
},
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Dict) -> Self:
"""Create an instance of Tag from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"name": obj.get("name")
})
return _obj
id: Optional[int] = Field(alias="id", default=None)
name: Optional[str] = Field(alias="name", default=None)
Tag.update_forward_refs()

View File

@@ -1,38 +1,104 @@
# coding: utf-8
from __future__ import annotations
from datetime import date, datetime # noqa: F401
"""
OpenAPI Petstore
import re # noqa: F401
from typing import Any, Dict, List, Optional # noqa: F401
This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
from pydantic import AnyUrl, BaseModel, EmailStr, Field, validator # noqa: F401
class User(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
The version of the OpenAPI document: 1.0.0
Generated by OpenAPI Generator (https://openapi-generator.tech)
Do not edit the class manually.
""" # noqa: E501
User - a model defined in OpenAPI
id: The id of this User [Optional].
username: The username of this User [Optional].
first_name: The first_name of this User [Optional].
last_name: The last_name of this User [Optional].
email: The email of this User [Optional].
password: The password of this User [Optional].
phone: The phone of this User [Optional].
user_status: The user_status of this User [Optional].
from __future__ import annotations
import pprint
import re # noqa: F401
import json
from pydantic import BaseModel, Field, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional
try:
from typing import Self
except ImportError:
from typing_extensions import Self
class User(BaseModel):
"""
A User who is purchasing from the pet store
""" # noqa: E501
id: Optional[StrictInt] = None
username: Optional[StrictStr] = None
first_name: Optional[StrictStr] = Field(default=None, alias="firstName")
last_name: Optional[StrictStr] = Field(default=None, alias="lastName")
email: Optional[StrictStr] = None
password: Optional[StrictStr] = None
phone: Optional[StrictStr] = None
user_status: Optional[StrictInt] = Field(default=None, description="User Status", alias="userStatus")
__properties: ClassVar[List[str]] = ["id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus"]
model_config = {
"populate_by_name": True,
"validate_assignment": True,
"protected_namespaces": (),
}
def to_str(self) -> str:
"""Returns the string representation of the model using alias"""
return pprint.pformat(self.model_dump(by_alias=True))
def to_json(self) -> str:
"""Returns the JSON representation of the model using alias"""
# TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
return json.dumps(self.to_dict())
@classmethod
def from_json(cls, json_str: str) -> Self:
"""Create an instance of User from a JSON string"""
return cls.from_dict(json.loads(json_str))
def to_dict(self) -> Dict[str, Any]:
"""Return the dictionary representation of the model using alias.
This has the following differences from calling pydantic's
`self.model_dump(by_alias=True)`:
* `None` is only added to the output dict for nullable fields that
were set at model initialization. Other fields with value `None`
are ignored.
"""
_dict = self.model_dump(
by_alias=True,
exclude={
},
exclude_none=True,
)
return _dict
@classmethod
def from_dict(cls, obj: Dict) -> Self:
"""Create an instance of User from a dict"""
if obj is None:
return None
if not isinstance(obj, dict):
return cls.model_validate(obj)
_obj = cls.model_validate({
"id": obj.get("id"),
"username": obj.get("username"),
"firstName": obj.get("firstName"),
"lastName": obj.get("lastName"),
"email": obj.get("email"),
"password": obj.get("password"),
"phone": obj.get("phone"),
"userStatus": obj.get("userStatus")
})
return _obj
id: Optional[int] = Field(alias="id", default=None)
username: Optional[str] = Field(alias="username", default=None)
first_name: Optional[str] = Field(alias="firstName", default=None)
last_name: Optional[str] = Field(alias="lastName", default=None)
email: Optional[str] = Field(alias="email", default=None)
password: Optional[str] = Field(alias="password", default=None)
phone: Optional[str] = Field(alias="phone", default=None)
user_status: Optional[int] = Field(alias="userStatus", default=None)
User.update_forward_refs()