Skip to content

Commit 28088c3

Browse files
NatalyaGrigorevaNatalia Grigoreva
authored andcommitted
update pydantic package to v2
1 parent 125b23f commit 28088c3

File tree

143 files changed

+3016
-5418
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

143 files changed

+3016
-5418
lines changed

.github/workflows/testing.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ jobs:
3939
python-version: ${{ matrix.python-version }}
4040
- name: Install poetry
4141
run: |
42-
python -m pip install --upgrade pip poetry==1.8.2 pre-commit
42+
python -m pip install --upgrade pip poetry==1.8.4 pre-commit
4343
poetry config virtualenvs.create false --local
4444
- name: Install dependencies
4545
run: poetry install --all-extras
@@ -87,7 +87,7 @@ jobs:
8787
python-version: ${{ matrix.python-version }}
8888
- name: Install poetry
8989
run: |
90-
python -m pip install --upgrade pip poetry==1.8.2 pre-commit
90+
python -m pip install --upgrade pip poetry==1.8.4 pre-commit
9191
poetry config virtualenvs.create false --local
9292
- name: Install dependencies
9393
run: poetry install --all-extras

.gitignore

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,9 +160,6 @@ cython_debug/
160160
.idea/
161161

162162
/.python-version
163-
/examples/api_for_tortoise_orm/db.sqlite3
164-
/examples/api_for_tortoise_orm/db.sqlite3-shm
165-
/examples/api_for_tortoise_orm/db.sqlite3-wal
166163
/db.sqlite3
167164
/db.sqlite3-shm
168165
/db.sqlite3-wal

README.md

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,11 @@ Create a test.py file and copy the following code into it
3131

3232
```python
3333
from pathlib import Path
34-
from typing import Any, ClassVar, Dict
34+
from typing import Any, ClassVar
3535

3636
import uvicorn
3737
from fastapi import APIRouter, Depends, FastAPI
38+
from pydantic import ConfigDict
3839
from sqlalchemy import Column, Integer, Text
3940
from sqlalchemy.engine import make_url
4041
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
@@ -61,12 +62,11 @@ class User(Base):
6162

6263

6364
class UserAttributesBaseSchema(BaseModel):
64-
name: str
65-
66-
class Config:
67-
"""Pydantic schema config."""
65+
model_config = ConfigDict(
66+
from_attributes=True,
67+
)
6868

69-
orm_mode = True
69+
name: str
7070

7171

7272
class UserSchema(UserAttributesBaseSchema):
@@ -108,20 +108,21 @@ async def sqlalchemy_init() -> None:
108108

109109

110110
class SessionDependency(BaseModel):
111-
session: AsyncSession = Depends(Connector.get_session)
111+
model_config = ConfigDict(
112+
arbitrary_types_allowed=True,
113+
)
112114

113-
class Config:
114-
arbitrary_types_allowed = True
115+
session: AsyncSession = Depends(Connector.get_session)
115116

116117

117-
def session_dependency_handler(view: ViewBase, dto: SessionDependency) -> Dict[str, Any]:
118+
def session_dependency_handler(view: ViewBase, dto: SessionDependency) -> dict[str, Any]:
118119
return {
119120
"session": dto.session,
120121
}
121122

122123

123124
class UserDetailView(DetailViewBaseGeneric):
124-
method_dependencies: ClassVar[Dict[HTTPMethod, HTTPMethodConfig]] = {
125+
method_dependencies: ClassVar[dict[HTTPMethod, HTTPMethodConfig]] = {
125126
HTTPMethod.ALL: HTTPMethodConfig(
126127
dependencies=SessionDependency,
127128
prepare_data_layer_kwargs=session_dependency_handler,
@@ -130,7 +131,7 @@ class UserDetailView(DetailViewBaseGeneric):
130131

131132

132133
class UserListView(ListViewBaseGeneric):
133-
method_dependencies: ClassVar[Dict[HTTPMethod, HTTPMethodConfig]] = {
134+
method_dependencies: ClassVar[dict[HTTPMethod, HTTPMethodConfig]] = {
134135
HTTPMethod.ALL: HTTPMethodConfig(
135136
dependencies=SessionDependency,
136137
prepare_data_layer_kwargs=session_dependency_handler,
@@ -190,7 +191,7 @@ if __name__ == "__main__":
190191
host="0.0.0.0",
191192
port=8080,
192193
reload=True,
193-
app_dir=str(CURRENT_DIR),
194+
app_dir=f"{CURRENT_DIR}",
194195
)
195196
```
196197

docs/fastapi-jsonapi.rst

Lines changed: 0 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,6 @@ fastapi_jsonapi.data_layers.filtering.sqlalchemy module
2525
:undoc-members:
2626
:show-inheritance:
2727

28-
fastapi_jsonapi.data_layers.filtering.tortoise_operation module
29-
---------------------------------------------------------------
30-
31-
.. automodule:: fastapi_jsonapi.data_layers.filtering.tortoise_operation
32-
:members:
33-
:undoc-members:
34-
:show-inheritance:
35-
36-
fastapi_jsonapi.data_layers.filtering.tortoise_orm module
37-
---------------------------------------------------------
38-
39-
.. automodule:: fastapi_jsonapi.data_layers.filtering.tortoise_orm
40-
:members:
41-
:undoc-members:
42-
:show-inheritance:
43-
4428
fastapi_jsonapi.data_layers.sorting.sqlalchemy module
4529
-----------------------------------------------------
4630

@@ -49,14 +33,6 @@ fastapi_jsonapi.data_layers.sorting.sqlalchemy module
4933
:undoc-members:
5034
:show-inheritance:
5135

52-
fastapi_jsonapi.data_layers.sorting.tortoise_orm module
53-
-------------------------------------------------------
54-
55-
.. automodule:: fastapi_jsonapi.data_layers.sorting.tortoise_orm
56-
:members:
57-
:undoc-members:
58-
:show-inheritance:
59-
6036
fastapi_jsonapi.data_layers.base module
6137
---------------------------------------
6238

@@ -97,14 +73,6 @@ fastapi_jsonapi.data_layers.sqla_orm module
9773
:undoc-members:
9874
:show-inheritance:
9975

100-
fastapi_jsonapi.data_layers.tortoise_orm module
101-
-----------------------------------------------
102-
103-
.. automodule:: fastapi_jsonapi.data_layers.tortoise_orm
104-
:members:
105-
:undoc-members:
106-
:show-inheritance:
107-
10876
fastapi_jsonapi.api module
10977
--------------------------
11078

docs/http_snippets/snippets/example_atomic_five__mixed_actions_result

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ Content-Type: application/json
1818
"attributes": {
1919
"birth_city": "Saint Petersburg",
2020
"favourite_movies": "\"The Good, the Bad and the Ugly\", \"Once Upon a Time in America\"",
21-
"keys_to_ids_list": null,
2221
},
2322
"id": "2",
2423
"type": "user_bio"

docs/http_snippets/update_snippets_with_responses.py

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,10 @@ def __lt__(self, other):
5050

5151

5252
def run_request_for_module(module_name: str):
53-
log.info("Start processing %r", module_name)
53+
log.info("Start processing %s", module_name)
5454

5555
module_full_name = ".".join((SNIPPETS_DIR, module_name))
56-
log.debug("import module %s", module_full_name)
56+
log.debug("Import module %s", module_full_name)
5757
module = importlib.import_module(module_full_name)
5858

5959
log.info("Process module %s", module)
@@ -68,15 +68,11 @@ def run_request_for_module(module_name: str):
6868

6969
http_response_text.append(
7070
# "HTTP/1.1 201 Created"
71-
"{} {} {}".format(
72-
"HTTP/1.1",
73-
response.status_code,
74-
response_reason,
75-
)
71+
f"HTTP/1.1 {response.status_code} {response.status_code}"
7672
)
7773

7874
if ct := response.headers.get("content-type"):
79-
http_response_text.append("{}: {}".format("Content-Type", ct))
75+
http_response_text.append(f"Content-Type: {ct}")
8076
http_response_text.append("")
8177

8278
if response.content:
@@ -96,9 +92,9 @@ def run_request_for_module(module_name: str):
9692
result_file_name = "/".join((SNIPPETS_DIR, module_name + SNIPPET_RESULT_POSTFIX))
9793
with open(result_file_name, "w") as f:
9894
res = f.write(result_text)
99-
log.info("Wrote text (%s) to %r", res, result_file_name)
95+
log.info("Wrote text (%s) to %s", res, result_file_name)
10096

101-
log.info("Processed %r", module_name)
97+
log.info("Processed %s", module_name)
10298

10399

104100
def add_help_lines(lines: list, module_name: str) -> None:
@@ -145,13 +141,13 @@ def main():
145141
log.warning("Starting")
146142

147143
available_modules = os.listdir(SNIPPETS_DIR)
148-
log.debug("all available snippets: %s", available_modules)
144+
log.debug("All available snippets: %s", available_modules)
149145
modules_to_process = list(
150146
# exclude unknown
151147
filter(lambda name: name.startswith(args.prefix), available_modules)
152148
)
153149
modules_to_process.sort(key=StrOrderCRUD)
154-
log.warning("modules to process (with order): %s", modules_to_process)
150+
log.warning("Modules to process (with order): %s", modules_to_process)
155151

156152
result_help_text = []
157153
result_help_text.append("=" * 30)
@@ -162,7 +158,7 @@ def main():
162158
try:
163159
run_request_for_module(module_name)
164160
except Exception:
165-
log.exception("Could not process module %r, skipping", module_file)
161+
log.exception("Could not process module %s, skipping", module_file)
166162
else:
167163
if REMOVE_PYTHON_SNIPPET:
168164
os.unlink("/".join((SNIPPETS_DIR, module_file)))

docs/logical_data_abstraction.rst

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -45,26 +45,28 @@ Now let's create the logical abstraction to illustrate this concept.
4545
4646
from pydantic import (
4747
BaseModel,
48+
ConfigDict,
4849
Field,
4950
)
50-
from typing import List
5151
from datetime import datetime
5252
5353
5454
class UserSchema(BaseModel):
55-
class Config:
56-
orm_mode = True
55+
model_config = ConfigDict(
56+
from_attributes=True,
57+
)
5758
5859
id: int
5960
name: str
6061
email: str
6162
birth_date: datetime
62-
computers: List['ComputerSchema']
63+
computers: list['ComputerSchema']
6364
6465
6566
class ComputerSchema(BaseModel):
66-
class Config:
67-
orm_mode = True
67+
model_config = ConfigDict(
68+
from_attributes=True,
69+
)
6870
6971
id: int
7072
serial: str

docs/python_snippets/client_generated_id/schematic_example.py

Lines changed: 19 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import sys
22
from pathlib import Path
3-
from typing import ClassVar
3+
from typing import ClassVar, Annotated
44

55
import uvicorn
66
from fastapi import APIRouter, Depends, FastAPI
7-
from fastapi_jsonapi.schema_base import Field, BaseModel as PydanticBaseModel
7+
from fastapi_jsonapi.schema_base import BaseModel
8+
from pydantic import ConfigDict
89
from sqlalchemy import Column, Integer, Text
910
from sqlalchemy.engine import make_url
1011
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
@@ -13,30 +14,31 @@
1314

1415
from fastapi_jsonapi import RoutersJSONAPI, init
1516
from fastapi_jsonapi.misc.sqla.generics.base import DetailViewBaseGeneric, ListViewBaseGeneric
17+
from fastapi_jsonapi.types_metadata import ClientCanSetId
1618
from fastapi_jsonapi.views.utils import HTTPMethod, HTTPMethodConfig
1719
from fastapi_jsonapi.views.view_base import ViewBase
1820

1921
CURRENT_FILE = Path(__file__).resolve()
2022
CURRENT_DIR = CURRENT_FILE.parent
2123
PROJECT_DIR = CURRENT_DIR.parent.parent
2224
DB_URL = f"sqlite+aiosqlite:///{CURRENT_DIR.absolute()}/db.sqlite3"
23-
sys.path.append(str(PROJECT_DIR))
25+
sys.path.append(f"{PROJECT_DIR}")
2426

2527
Base = declarative_base()
2628

2729

2830
class User(Base):
2931
__tablename__ = "users"
32+
3033
id = Column(Integer, primary_key=True, autoincrement=False)
3134
name = Column(Text, nullable=True)
3235

3336

34-
class BaseModel(PydanticBaseModel):
35-
class Config:
36-
orm_mode = True
37-
38-
3937
class UserAttributesBaseSchema(BaseModel):
38+
model_config = ConfigDict(
39+
from_attributes=True,
40+
)
41+
4042
name: str
4143

4244

@@ -51,7 +53,7 @@ class UserPatchSchema(UserAttributesBaseSchema):
5153
class UserInSchema(UserAttributesBaseSchema):
5254
"""User input schema."""
5355

54-
id: int = Field(client_can_set_id=True)
56+
id: Annotated[int, ClientCanSetId()]
5557

5658

5759
async def get_session():
@@ -72,14 +74,17 @@ async def sqlalchemy_init() -> None:
7274

7375

7476
class SessionDependency(BaseModel):
75-
session: AsyncSession = Depends(get_session)
77+
model_config = ConfigDict(
78+
arbitrary_types_allowed=True,
79+
)
7680

77-
class Config:
78-
arbitrary_types_allowed = True
81+
session: AsyncSession = Depends(get_session)
7982

8083

8184
def session_dependency_handler(view: ViewBase, dto: SessionDependency) -> dict:
82-
return {"session": dto.session}
85+
return {
86+
"session": dto.session,
87+
}
8388

8489

8590
class UserDetailView(DetailViewBaseGeneric):
@@ -153,5 +158,5 @@ def create_app() -> FastAPI:
153158
host="0.0.0.0",
154159
port=8084,
155160
reload=True,
156-
app_dir=str(CURRENT_DIR),
161+
app_dir=f"{CURRENT_DIR}",
157162
)

docs/python_snippets/data_layer/custom_data_layer.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,6 @@
1010
class MyCustomDataLayer(BaseDataLayer):
1111
"""Overload abstract methods here"""
1212

13-
...
14-
1513

1614
class MyCustomSqlaDataLayer(SqlalchemyDataLayer):
1715
"""Overload any methods here"""

docs/python_snippets/relationships/models.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,9 @@
77

88
class User(Base, BaseModelMixin):
99
__tablename__ = "users"
10+
1011
id = Column(Integer, primary_key=True, autoincrement=True)
11-
name: str = Column(String)
12+
name = Column(String)
1213

1314
posts = relationship("Post", back_populates="user", uselist=True)
1415
bio = relationship("UserBio", back_populates="user", uselist=False)
@@ -20,14 +21,17 @@ class Computer(Base, BaseModelMixin):
2021

2122
id = Column(Integer, primary_key=True, autoincrement=True)
2223
name = Column(String, nullable=False)
24+
2325
user_id = Column(Integer, ForeignKey("users.id"), nullable=True)
2426
user = relationship("User", back_populates="computers")
2527

2628

2729
class UserBio(Base, BaseModelMixin):
2830
__tablename__ = "user_bio"
31+
2932
id = Column(Integer, primary_key=True, autoincrement=True)
30-
birth_city: str = Column(String, nullable=False, default="", server_default="")
31-
favourite_movies: str = Column(String, nullable=False, default="", server_default="")
33+
birth_city = Column(String, nullable=False, default="", server_default="")
34+
favourite_movies = Column(String, nullable=False, default="", server_default="")
35+
3236
user_id = Column(Integer, ForeignKey("users.id"), nullable=False, unique=True)
3337
user = relationship("User", back_populates="bio", uselist=False)

0 commit comments

Comments
 (0)