Skip to content

Commit 16e8c8a

Browse files
committed
[FIX] fix default template, separate pdm package prod <-> dev, test build
1 parent 82de5c4 commit 16e8c8a

File tree

5 files changed

+82
-85
lines changed

5 files changed

+82
-85
lines changed

.pre-commit-config.yaml

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,27 @@ repos:
1111
- id: check-yaml
1212
- id: check-toml
1313
- id: check-added-large-files
14+
15+
- repo: local
16+
hooks:
17+
- id: format
18+
name: format
19+
entry: bash scripts/format.sh
20+
language: system
21+
pass_filenames: false
22+
23+
- id: lint
24+
name: lint
25+
entry: bash scripts/lint.sh
26+
language: system
27+
pass_filenames: false
28+
29+
- id: test
30+
name: test
31+
entry: bash scripts/fetch-and-test.sh
32+
language: system
33+
pass_filenames: false
34+
1435
ci:
1536
autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
1637
autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate

fastapi-project-template/fastapi-default/src/crud/user.py-tpl

Lines changed: 20 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -7,79 +7,38 @@ from typing import Type
77
from uuid import UUID
88

99
from ._base import load_json
10-
11-
from sqlalchemy.exc import IntegrityError
12-
from sqlalchemy.ext.asyncio import AsyncSession
13-
from sqlmodel import select, delete
14-
15-
from src.schemas.user import UserSchema
16-
from src.db.models.user import UserCreate, User, UserUpdate
1710
from src.helper.exceptions import InternalException, ErrorCode
11+
from src.schemas.user import UserSchema, UserCreate, UserUpdate
12+
from src.helper.global_data import mock_user_data
1813

1914

20-
def get_mock_user_data(id: UUID, response_model: Type[UserSchema]):
21-
base_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
22-
file_path = os.path.join(base_path, "src", "mocks", "mock_users.json")
23-
users = load_json(file_path)
24-
user_data = next((user for user in users if user["id"] == str(id)), None)
15+
def get_mock_user_data(id: UUID) -> dict:
16+
user_data = next((user for user in mock_user_data if user["id"] == str(id)), None)
2517
if user_data is None:
2618
raise InternalException(
27-
message="ERROR : User not found.", error_code=ErrorCode.NOT_FOUND
19+
message="User not found.", error_code=ErrorCode.NOT_FOUND
2820
)
29-
return response_model(**user_data)
21+
return user_data
3022

3123

32-
async def create_user(db: AsyncSession, user: UserCreate) -> User:
33-
db_user = User(**user.dict())
34-
try:
35-
db.add(db_user)
36-
await db.commit()
37-
await db.refresh(db_user)
38-
return db_user
39-
except IntegrityError:
40-
await db.rollback()
24+
def create_mock_user(user: UserCreate) -> dict:
25+
new_user = user.model_dump()
26+
if any(u["email"] == new_user["email"] for u in mock_user_data):
4127
raise InternalException(
4228
error_code=ErrorCode.CONFLICT,
43-
message="ERROR : This user is already exist.",
29+
message="This user is already exist.",
4430
)
31+
mock_user_data.append(new_user)
32+
return new_user
4533

4634

47-
async def get_user(db: AsyncSession, id: UUID) -> User:
48-
query = select(User).where(User.id == id)
49-
response = await db.execute(query)
50-
return response.scalar_one_or_none()
51-
52-
53-
async def get_user_by_email(db: AsyncSession, email: str) -> User:
54-
query = select(User).where(User.email == email)
55-
response = await db.execute(query)
56-
return response.scalar_one_or_none()
57-
58-
59-
async def update_user(db: AsyncSession, id: UUID, user: UserUpdate) -> User:
60-
db_user = await get_user(db, id)
61-
if not db_user:
62-
raise InternalException(
63-
error_code=ErrorCode.NOT_FOUND, message="ERROR : User not found."
64-
)
65-
66-
for k, v in user.dict(exclude_unset=True).items():
67-
setattr(db_user, k, v)
68-
69-
try:
70-
await db.commit()
71-
await db.refresh(db_user)
72-
return db_user
73-
except IntegrityError:
74-
await db.rollback()
75-
raise InternalException(
76-
error_code=ErrorCode.CONFLICT,
77-
message="ERROR : There is information that overlaps with other user information.",
78-
)
35+
def update_mock_user(id: UUID, user: UserUpdate) -> dict:
36+
user_data = get_mock_user_data(id)
37+
update_data = user.model_dump(exclude_unset=True)
38+
user_data.update(update_data)
39+
return user_data
7940

8041

81-
async def delete_user(db: AsyncSession, id: UUID) -> int:
82-
query = delete(User).where(User.id == id)
83-
response = await db.execute(query)
84-
await db.commit()
85-
return response.rowcount
42+
def delete_mock_user(id: UUID) -> None:
43+
user_data = get_mock_user_data(id)
44+
mock_user_data.remove(user_data)

fastapi-project-template/fastapi-default/src/helper/global_data.py-tpl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def initialize_mock_data() -> None:
1818

1919
# If the model has relations with other model,
2020
# you can map it their respective columns like below:
21-
item_data = json.loads(json.dumps({'some': 'item', "user_id": "123e4567-e89b-12d3-a456-426614174000"}))
21+
item_data = [{'some': 'item', "user_id": "123e4567-e89b-12d3-a456-426614174000"}]
2222
item_map = {}
2323
for item in item_data:
2424
user_id = item["user_id"]

fastapi-project-template/fastapi-default/src/router/user.py-tpl

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
# --------------------------------------------------------------------------
44
from . import *
55

6-
from src import mock_user_data
6+
from src.helper.global_data import mock_user_data
77
from src.crud.user import get_mock_user_data
88
from src.schemas import ResponseSchema
99
from src.schemas.user import UserSchema, UserCreate, UserUpdate
@@ -28,23 +28,23 @@ def generate_new_user_id():
2828
)
2929
async def create_user_route(
3030
data: UserCreate,
31+
request: Request,
3132
):
32-
new_user = {
33-
"id": generate_new_user_id(),
34-
"username": data.username,
35-
"email": data.email,
36-
"createdAt": datetime.utcnow().isoformat() + "Z",
37-
"modifiedAt": datetime.utcnow().isoformat() + "Z",
38-
}
39-
mock_user_data.append(new_user)
40-
response = ResponseSchema(
41-
timestamp=datetime.utcnow().isoformat() + "Z",
42-
status=201,
43-
code="HTTP-201",
44-
path=str(request.url),
45-
message=UserSchema(**new_user),
46-
)
47-
return response
33+
try:
34+
new_user = create_mock_user(data)
35+
response = ResponseSchema(
36+
timestamp=datetime.utcnow().isoformat() + "Z",
37+
status=201,
38+
code="HTTP-201",
39+
path=str(request.url),
40+
message=UserSchema(**new_user),
41+
)
42+
return response
43+
except InternalException as e:
44+
return JSONResponse(
45+
status_code=e.status,
46+
content=e.to_response(path=str(request.url)).model_dump(),
47+
)
4848

4949

5050
@router.get(

pyproject.toml

Lines changed: 23 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,21 @@ authors = [
88
dependencies = [
99
"click>=8.1.7",
1010
"rich>=13.9.2",
11+
"fastapi-cli>=0.0.5",
12+
]
13+
requires-python = ">=3.12"
14+
readme = "README.md"
15+
license = {text = "MIT"}
16+
17+
[project.optional-dependencies]
18+
dev = [
1119
"pytest>=8.3.3",
20+
"pytest-cov>=5.0.0",
1221
"black>=24.10.0",
1322
"pre-commit>=4.0.1",
14-
"pytest-cov>=5.0.0",
1523
"mypy>=1.12.0",
1624
"isort>=5.13.2",
17-
"fastapi-cli>=0.0.5",
1825
]
19-
requires-python = ">=3.12"
20-
readme = "README.md"
21-
license = {text = "MIT"}
2226

2327
[project.scripts]
2428
fastkit = "fastapi_fastkit.cli:fastkit_cli"
@@ -27,11 +31,24 @@ fastkit = "fastapi_fastkit.cli:fastkit_cli"
2731
requires = ["pdm-backend"]
2832
build-backend = "pdm.backend"
2933

30-
3134
[tool.pdm]
3235
version = { source = "file", path = "src/fastapi_fastkit/__init__.py" }
3336
distribution = true
3437

38+
[tool.pdm.dev-dependencies]
39+
test = [
40+
"pytest>=8.3.3",
41+
"pytest-cov>=5.0.0",
42+
]
43+
lint = [
44+
"black>=24.10.0",
45+
"mypy>=1.12.0",
46+
"isort>=5.13.2",
47+
]
48+
dev = [
49+
"pre-commit>=4.0.1",
50+
]
51+
3552
[tool.pytest.ini_options]
3653
testpaths = ["test"]
3754
python_files = "test_*.py"

0 commit comments

Comments
 (0)