FastAPI-fastkit 1.0.0__py3-none-any.whl → 1.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. fastapi_fastkit/__init__.py +10 -1
  2. fastapi_fastkit/backend/main.py +482 -482
  3. fastapi_fastkit/backend/transducer.py +106 -106
  4. fastapi_fastkit/cli.py +664 -631
  5. fastapi_fastkit/core/settings.py +155 -155
  6. fastapi_fastkit/fastapi_project_template/README.md +90 -90
  7. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.env-tpl +1 -1
  8. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/.gitignore-tpl +30 -30
  9. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/README.md-tpl +107 -107
  10. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/requirements.txt-tpl +36 -36
  11. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/scripts/format.sh-tpl +5 -5
  12. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/scripts/lint.sh-tpl +5 -5
  13. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/scripts/run-server.sh-tpl +8 -8
  14. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/scripts/test.sh-tpl +6 -6
  15. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/setup.cfg-tpl +14 -14
  16. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/setup.py-tpl +25 -25
  17. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/api.py-tpl +9 -9
  18. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/api/routes/items.py-tpl +57 -57
  19. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/core/config.py-tpl +64 -64
  20. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/crud/items.py-tpl +21 -21
  21. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/main.py-tpl +26 -26
  22. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/mocks/mock_items.json-tpl +8 -8
  23. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/src/schemas/items.py-tpl +22 -22
  24. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/conftest.py-tpl +42 -42
  25. fastapi_fastkit/fastapi_project_template/fastapi-async-crud/tests/test_items.py-tpl +48 -48
  26. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.env-tpl +1 -1
  27. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/.gitignore-tpl +191 -191
  28. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/README.md-tpl +156 -156
  29. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/requirements.txt-tpl +36 -36
  30. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/scripts/format.sh-tpl +5 -5
  31. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/scripts/lint.sh-tpl +5 -5
  32. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/scripts/run-server.sh-tpl +8 -8
  33. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/scripts/test.sh-tpl +6 -6
  34. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/setup.cfg-tpl +12 -12
  35. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/setup.py-tpl +27 -27
  36. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/.DS_Store +0 -0
  37. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/api/api.py-tpl +9 -9
  38. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/api/routes/items.py-tpl +172 -172
  39. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/core/config.py-tpl +64 -64
  40. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/crud/items.py-tpl +21 -21
  41. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/helper/exceptions.py-tpl +103 -103
  42. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/helper/pagination.py-tpl +72 -72
  43. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/main.py-tpl +39 -39
  44. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/mocks/mock_items.json-tpl +8 -8
  45. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/schemas/base.py-tpl +49 -49
  46. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/schemas/items.py-tpl +22 -22
  47. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/src/utils/documents.py-tpl +20 -20
  48. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/conftest.py-tpl +42 -42
  49. fastapi_fastkit/fastapi_project_template/fastapi-custom-response/tests/test_items.py-tpl +61 -61
  50. fastapi_fastkit/fastapi_project_template/fastapi-default/README.md-tpl +101 -101
  51. fastapi_fastkit/fastapi_project_template/fastapi-default/scripts/run-server.sh-tpl +8 -8
  52. fastapi_fastkit/fastapi_project_template/fastapi-default/setup.py-tpl +22 -22
  53. fastapi_fastkit/fastapi_project_template/fastapi-default/src/mocks/mock_items.json-tpl +8 -8
  54. fastapi_fastkit/fastapi_project_template/fastapi-default/tests/conftest.py-tpl +30 -30
  55. fastapi_fastkit/fastapi_project_template/fastapi-default/tests/test_items.py-tpl +44 -44
  56. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.env-tpl +1 -1
  57. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/.gitignore-tpl +30 -30
  58. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/Dockerfile-tpl +23 -23
  59. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/README.md-tpl +119 -119
  60. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/requirements.txt-tpl +36 -36
  61. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/scripts/format.sh-tpl +5 -5
  62. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/scripts/lint.sh-tpl +5 -5
  63. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/scripts/run-server.sh-tpl +8 -8
  64. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/scripts/test.sh-tpl +6 -6
  65. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/setup.cfg-tpl +13 -13
  66. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/setup.py-tpl +22 -22
  67. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/api.py-tpl +6 -6
  68. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/api/routes/items.py-tpl +54 -54
  69. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/core/config.py-tpl +64 -64
  70. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/crud/items.py-tpl +15 -15
  71. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/main.py-tpl +26 -26
  72. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/mocks/mock_items.json-tpl +8 -8
  73. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/src/schemas/items.py-tpl +19 -19
  74. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/conftest.py-tpl +30 -30
  75. fastapi_fastkit/fastapi_project_template/fastapi-dockerized/tests/test_items.py-tpl +44 -44
  76. fastapi_fastkit/fastapi_project_template/fastapi-empty/.env-tpl +1 -1
  77. fastapi_fastkit/fastapi_project_template/fastapi-empty/setup.py-tpl +22 -22
  78. fastapi_fastkit/fastapi_project_template/fastapi-empty/src/core/config.py-tpl +75 -75
  79. fastapi_fastkit/fastapi_project_template/fastapi-empty/src/main.py-tpl +36 -36
  80. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.env-tpl +9 -9
  81. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/.gitignore-tpl +30 -30
  82. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/Dockerfile-tpl +23 -23
  83. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/README.md-tpl +144 -144
  84. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/alembic.ini-tpl +119 -119
  85. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/docker-compose.yml-tpl +44 -44
  86. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/requirements.txt-tpl +41 -41
  87. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/format.sh-tpl +5 -5
  88. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/lint.sh-tpl +5 -5
  89. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/pre-start.sh-tpl +16 -16
  90. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/run-server.sh-tpl +8 -8
  91. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/scripts/test.sh-tpl +10 -10
  92. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/setup.cfg-tpl +13 -13
  93. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/setup.py-tpl +25 -25
  94. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/README-tpl +1 -1
  95. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/env.py-tpl +85 -85
  96. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/script.py.mako-tpl +26 -26
  97. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/alembic/versions/bedcdc35b64a_first_alembic.py-tpl +37 -37
  98. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/api.py-tpl +11 -11
  99. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/deps.py-tpl +19 -19
  100. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/api/routes/items.py-tpl +109 -109
  101. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/config.py-tpl +88 -88
  102. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/core/db.py-tpl +53 -53
  103. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/crud/items.py-tpl +102 -102
  104. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/main.py-tpl +45 -45
  105. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/schemas/items.py-tpl +54 -54
  106. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/utils/backend_pre_start.py-tpl +39 -39
  107. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/utils/init_data.py-tpl +23 -23
  108. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/src/utils/tests_pre_start.py-tpl +39 -39
  109. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/conftest.py-tpl +63 -63
  110. fastapi_fastkit/fastapi_project_template/fastapi-psql-orm/tests/test_items.py-tpl +44 -44
  111. fastapi_fastkit/fastapi_project_template/modules/api/routes/new_route.py-tpl +64 -64
  112. fastapi_fastkit/fastapi_project_template/modules/crud/new_route.py-tpl +29 -29
  113. fastapi_fastkit/fastapi_project_template/modules/schemas/new_route.py-tpl +23 -23
  114. fastapi_fastkit/logs/fastkit_debug_20250702_161423.log +21 -0
  115. fastapi_fastkit/logs/fastkit_debug_20250702_162706.log +20 -0
  116. fastapi_fastkit/logs/fastkit_debug_20250702_163010.log +21 -0
  117. fastapi_fastkit/logs/fastkit_debug_20250702_163526.log +21 -0
  118. fastapi_fastkit/logs/fastkit_debug_20250702_164053.log +21 -0
  119. fastapi_fastkit/logs/fastkit_debug_20250702_165220.log +21 -0
  120. fastapi_fastkit/logs/fastkit_debug_20250702_165647.log +21 -0
  121. fastapi_fastkit/utils/logging.py +112 -1
  122. fastapi_fastkit/utils/main.py +140 -129
  123. fastapi_fastkit-1.0.2.dist-info/METADATA +320 -0
  124. {fastapi_fastkit-1.0.0.dist-info → fastapi_fastkit-1.0.2.dist-info}/RECORD +127 -119
  125. {fastapi_fastkit-1.0.0.dist-info → fastapi_fastkit-1.0.2.dist-info}/WHEEL +1 -1
  126. {fastapi_fastkit-1.0.0.dist-info → fastapi_fastkit-1.0.2.dist-info}/licenses/LICENSE +21 -21
  127. fastapi_fastkit-1.0.0.dist-info/METADATA +0 -208
  128. {fastapi_fastkit-1.0.0.dist-info → fastapi_fastkit-1.0.2.dist-info}/entry_points.txt +0 -0
@@ -1,88 +1,88 @@
1
- # --------------------------------------------------------------------------
2
- # Configuration module
3
- # --------------------------------------------------------------------------
4
- import secrets
5
- import warnings
6
- from typing import Annotated, Any, Literal
7
-
8
- from pydantic import (
9
- AnyUrl,
10
- BeforeValidator,
11
- PostgresDsn,
12
- computed_field,
13
- model_validator,
14
- )
15
- from pydantic_core import MultiHostUrl
16
- from pydantic_settings import BaseSettings, SettingsConfigDict
17
- from typing_extensions import Self
18
-
19
-
20
- def parse_cors(v: Any) -> list[str] | str:
21
- if isinstance(v, str) and not v.startswith("["):
22
- return [i.strip() for i in v.split(",")]
23
- elif isinstance(v, list | str):
24
- return v
25
- raise ValueError(v)
26
-
27
-
28
- class Settings(BaseSettings):
29
- model_config = SettingsConfigDict(
30
- env_file=".env",
31
- env_ignore_empty=True,
32
- extra="ignore",
33
- )
34
-
35
- SECRET_KEY: str = secrets.token_urlsafe(32)
36
- ENVIRONMENT: Literal["development", "production"] = "development"
37
-
38
- CLIENT_ORIGIN: str = ""
39
-
40
- BACKEND_CORS_ORIGINS: Annotated[list[AnyUrl] | str, BeforeValidator(parse_cors)] = (
41
- []
42
- )
43
-
44
- @computed_field # type: ignore[prop-decorator]
45
- @property
46
- def all_cors_origins(self) -> list[str]:
47
- return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + [
48
- self.CLIENT_ORIGIN
49
- ]
50
-
51
- PROJECT_NAME: str = "<project_name>"
52
- POSTGRES_SERVER: str
53
- POSTGRES_PORT: int = 5432
54
- POSTGRES_USER: str
55
- POSTGRES_PASSWORD: str = ""
56
- POSTGRES_DB: str = ""
57
-
58
- @computed_field # type: ignore[prop-decorator]
59
- @property
60
- def SQLALCHEMY_DATABASE_URI(self) -> PostgresDsn:
61
- return MultiHostUrl.build( # type: ignore
62
- scheme="postgresql+psycopg",
63
- username=self.POSTGRES_USER,
64
- password=self.POSTGRES_PASSWORD,
65
- host=self.POSTGRES_SERVER,
66
- port=self.POSTGRES_PORT,
67
- path=self.POSTGRES_DB,
68
- )
69
-
70
- def _check_default_secret(self, var_name: str, value: str | None) -> None:
71
- if value == "changethis":
72
- message = (
73
- f'The value of {var_name} is "changethis", '
74
- "for security, please change it, at least for deployments."
75
- )
76
- if self.ENVIRONMENT == "development":
77
- warnings.warn(message, stacklevel=1)
78
- else:
79
- raise ValueError(message)
80
-
81
- @model_validator(mode="after")
82
- def _enforce_non_default_secrets(self) -> Self:
83
- self._check_default_secret("SECRET_KEY", self.SECRET_KEY)
84
-
85
- return self
86
-
87
-
88
- settings = Settings() # type: ignore
1
+ # --------------------------------------------------------------------------
2
+ # Configuration module
3
+ # --------------------------------------------------------------------------
4
+ import secrets
5
+ import warnings
6
+ from typing import Annotated, Any, Literal
7
+
8
+ from pydantic import (
9
+ AnyUrl,
10
+ BeforeValidator,
11
+ PostgresDsn,
12
+ computed_field,
13
+ model_validator,
14
+ )
15
+ from pydantic_core import MultiHostUrl
16
+ from pydantic_settings import BaseSettings, SettingsConfigDict
17
+ from typing_extensions import Self
18
+
19
+
20
+ def parse_cors(v: Any) -> list[str] | str:
21
+ if isinstance(v, str) and not v.startswith("["):
22
+ return [i.strip() for i in v.split(",")]
23
+ elif isinstance(v, list | str):
24
+ return v
25
+ raise ValueError(v)
26
+
27
+
28
+ class Settings(BaseSettings):
29
+ model_config = SettingsConfigDict(
30
+ env_file=".env",
31
+ env_ignore_empty=True,
32
+ extra="ignore",
33
+ )
34
+
35
+ SECRET_KEY: str = secrets.token_urlsafe(32)
36
+ ENVIRONMENT: Literal["development", "production"] = "development"
37
+
38
+ CLIENT_ORIGIN: str = ""
39
+
40
+ BACKEND_CORS_ORIGINS: Annotated[list[AnyUrl] | str, BeforeValidator(parse_cors)] = (
41
+ []
42
+ )
43
+
44
+ @computed_field # type: ignore[prop-decorator]
45
+ @property
46
+ def all_cors_origins(self) -> list[str]:
47
+ return [str(origin).rstrip("/") for origin in self.BACKEND_CORS_ORIGINS] + [
48
+ self.CLIENT_ORIGIN
49
+ ]
50
+
51
+ PROJECT_NAME: str = "<project_name>"
52
+ POSTGRES_SERVER: str
53
+ POSTGRES_PORT: int = 5432
54
+ POSTGRES_USER: str
55
+ POSTGRES_PASSWORD: str = ""
56
+ POSTGRES_DB: str = ""
57
+
58
+ @computed_field # type: ignore[prop-decorator]
59
+ @property
60
+ def SQLALCHEMY_DATABASE_URI(self) -> PostgresDsn:
61
+ return MultiHostUrl.build( # type: ignore
62
+ scheme="postgresql+psycopg",
63
+ username=self.POSTGRES_USER,
64
+ password=self.POSTGRES_PASSWORD,
65
+ host=self.POSTGRES_SERVER,
66
+ port=self.POSTGRES_PORT,
67
+ path=self.POSTGRES_DB,
68
+ )
69
+
70
+ def _check_default_secret(self, var_name: str, value: str | None) -> None:
71
+ if value == "changethis":
72
+ message = (
73
+ f'The value of {var_name} is "changethis", '
74
+ "for security, please change it, at least for deployments."
75
+ )
76
+ if self.ENVIRONMENT == "development":
77
+ warnings.warn(message, stacklevel=1)
78
+ else:
79
+ raise ValueError(message)
80
+
81
+ @model_validator(mode="after")
82
+ def _enforce_non_default_secrets(self) -> Self:
83
+ self._check_default_secret("SECRET_KEY", self.SECRET_KEY)
84
+
85
+ return self
86
+
87
+
88
+ settings = Settings() # type: ignore
@@ -1,53 +1,53 @@
1
- # --------------------------------------------------------------------------
2
- # Database configuration module
3
- # --------------------------------------------------------------------------
4
- from sqlmodel import Session, SQLModel, create_engine, select
5
-
6
- from src.core.config import settings
7
- from src.schemas.items import ItemBase
8
-
9
- engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI))
10
-
11
-
12
- # make sure all SQLModel models are imported (src.schemas) before initializing DB
13
- # otherwise, SQLModel might fail to initialize relationships properly
14
-
15
-
16
- def init_db(session: Session) -> None:
17
- """
18
- Initialize the database with sample data.
19
-
20
- This function can be used to seed the database with initial data for testing or
21
- demonstration purposes. Modify the sample data as needed for your application.
22
-
23
- Args:
24
- session: Database session
25
- """
26
- # Check if we already have items
27
- statement = select(ItemBase)
28
- results = session.exec(statement).all()
29
- if results:
30
- return # Database already has data
31
-
32
- # Add sample items
33
- sample_items = [
34
- {"name": "Test Item 1", "description": "This is a test item", "price": 19.99, "category": "test"},
35
- {"name": "Test Item 2", "description": "Another test item", "price": 29.99, "category": "test"},
36
- ]
37
-
38
- for item_data in sample_items:
39
- item = ItemBase(**item_data)
40
- session.add(item)
41
-
42
- session.commit()
43
-
44
-
45
- def create_db_and_tables():
46
- """
47
- Create database tables.
48
-
49
- This function creates all tables defined via SQLModel. In production,
50
- use Alembic migrations instead of this function.
51
- """
52
- # SQLModel.metadata.create_all(engine)
53
- pass
1
+ # --------------------------------------------------------------------------
2
+ # Database configuration module
3
+ # --------------------------------------------------------------------------
4
+ from sqlmodel import Session, SQLModel, create_engine, select
5
+
6
+ from src.core.config import settings
7
+ from src.schemas.items import ItemBase
8
+
9
+ engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI))
10
+
11
+
12
+ # make sure all SQLModel models are imported (src.schemas) before initializing DB
13
+ # otherwise, SQLModel might fail to initialize relationships properly
14
+
15
+
16
+ def init_db(session: Session) -> None:
17
+ """
18
+ Initialize the database with sample data.
19
+
20
+ This function can be used to seed the database with initial data for testing or
21
+ demonstration purposes. Modify the sample data as needed for your application.
22
+
23
+ Args:
24
+ session: Database session
25
+ """
26
+ # Check if we already have items
27
+ statement = select(ItemBase)
28
+ results = session.exec(statement).all()
29
+ if results:
30
+ return # Database already has data
31
+
32
+ # Add sample items
33
+ sample_items = [
34
+ {"name": "Test Item 1", "description": "This is a test item", "price": 19.99, "category": "test"},
35
+ {"name": "Test Item 2", "description": "Another test item", "price": 29.99, "category": "test"},
36
+ ]
37
+
38
+ for item_data in sample_items:
39
+ item = ItemBase(**item_data)
40
+ session.add(item)
41
+
42
+ session.commit()
43
+
44
+
45
+ def create_db_and_tables():
46
+ """
47
+ Create database tables.
48
+
49
+ This function creates all tables defined via SQLModel. In production,
50
+ use Alembic migrations instead of this function.
51
+ """
52
+ # SQLModel.metadata.create_all(engine)
53
+ pass
@@ -1,102 +1,102 @@
1
- # --------------------------------------------------------------------------
2
- # Item CRUD method module
3
- # --------------------------------------------------------------------------
4
- from typing import Dict, List, Optional, Union
5
-
6
- from sqlmodel import Session, select
7
-
8
- from src.core.db import engine
9
- from src.schemas.items import ItemBase
10
-
11
-
12
- def get_item(db: Session, item_id: int) -> Optional[ItemBase]:
13
- """
14
- Retrieve a single item by its ID.
15
-
16
- Args:
17
- db: Database session
18
- item_id: ID of the item to retrieve
19
-
20
- Returns:
21
- The item if found, None otherwise
22
- """
23
- return db.get(ItemBase, item_id)
24
-
25
-
26
- def get_items(db: Session, skip: int = 0, limit: int = 100) -> List[ItemBase]:
27
- """
28
- Retrieve a list of items with pagination.
29
-
30
- Args:
31
- db: Database session
32
- skip: Number of records to skip (for pagination)
33
- limit: Maximum number of records to return
34
-
35
- Returns:
36
- List of items
37
- """
38
- statement = select(ItemBase).offset(skip).limit(limit)
39
- return list(db.exec(statement).all())
40
-
41
-
42
- def create_item(db: Session, item: Dict[str, Union[str, float]]) -> ItemBase:
43
- """
44
- Create a new item in the database.
45
-
46
- Args:
47
- db: Database session
48
- item: Dictionary containing item data
49
-
50
- Returns:
51
- The created item
52
- """
53
- db_item = ItemBase(**item)
54
- db.add(db_item)
55
- db.commit()
56
- db.refresh(db_item)
57
- return db_item
58
-
59
-
60
- def update_item(db: Session, item_id: int, item_data: Dict[str, Union[str, float]]) -> Optional[ItemBase]:
61
- """
62
- Update an existing item.
63
-
64
- Args:
65
- db: Database session
66
- item_id: ID of the item to update
67
- item_data: Dictionary containing updated item data
68
-
69
- Returns:
70
- The updated item if found, None otherwise
71
- """
72
- db_item = get_item(db, item_id)
73
- if not db_item:
74
- return None
75
-
76
- for key, value in item_data.items():
77
- setattr(db_item, key, value)
78
-
79
- db.add(db_item)
80
- db.commit()
81
- db.refresh(db_item)
82
- return db_item
83
-
84
-
85
- def delete_item(db: Session, item_id: int) -> bool:
86
- """
87
- Delete an item from the database.
88
-
89
- Args:
90
- db: Database session
91
- item_id: ID of the item to delete
92
-
93
- Returns:
94
- True if the item was deleted, False if not found
95
- """
96
- db_item = get_item(db, item_id)
97
- if not db_item:
98
- return False
99
-
100
- db.delete(db_item)
101
- db.commit()
102
- return True
1
+ # --------------------------------------------------------------------------
2
+ # Item CRUD method module
3
+ # --------------------------------------------------------------------------
4
+ from typing import Dict, List, Optional, Union
5
+
6
+ from sqlmodel import Session, select
7
+
8
+ from src.core.db import engine
9
+ from src.schemas.items import ItemBase
10
+
11
+
12
+ def get_item(db: Session, item_id: int) -> Optional[ItemBase]:
13
+ """
14
+ Retrieve a single item by its ID.
15
+
16
+ Args:
17
+ db: Database session
18
+ item_id: ID of the item to retrieve
19
+
20
+ Returns:
21
+ The item if found, None otherwise
22
+ """
23
+ return db.get(ItemBase, item_id)
24
+
25
+
26
+ def get_items(db: Session, skip: int = 0, limit: int = 100) -> List[ItemBase]:
27
+ """
28
+ Retrieve a list of items with pagination.
29
+
30
+ Args:
31
+ db: Database session
32
+ skip: Number of records to skip (for pagination)
33
+ limit: Maximum number of records to return
34
+
35
+ Returns:
36
+ List of items
37
+ """
38
+ statement = select(ItemBase).offset(skip).limit(limit)
39
+ return list(db.exec(statement).all())
40
+
41
+
42
+ def create_item(db: Session, item: Dict[str, Union[str, float]]) -> ItemBase:
43
+ """
44
+ Create a new item in the database.
45
+
46
+ Args:
47
+ db: Database session
48
+ item: Dictionary containing item data
49
+
50
+ Returns:
51
+ The created item
52
+ """
53
+ db_item = ItemBase(**item)
54
+ db.add(db_item)
55
+ db.commit()
56
+ db.refresh(db_item)
57
+ return db_item
58
+
59
+
60
+ def update_item(db: Session, item_id: int, item_data: Dict[str, Union[str, float]]) -> Optional[ItemBase]:
61
+ """
62
+ Update an existing item.
63
+
64
+ Args:
65
+ db: Database session
66
+ item_id: ID of the item to update
67
+ item_data: Dictionary containing updated item data
68
+
69
+ Returns:
70
+ The updated item if found, None otherwise
71
+ """
72
+ db_item = get_item(db, item_id)
73
+ if not db_item:
74
+ return None
75
+
76
+ for key, value in item_data.items():
77
+ setattr(db_item, key, value)
78
+
79
+ db.add(db_item)
80
+ db.commit()
81
+ db.refresh(db_item)
82
+ return db_item
83
+
84
+
85
+ def delete_item(db: Session, item_id: int) -> bool:
86
+ """
87
+ Delete an item from the database.
88
+
89
+ Args:
90
+ db: Database session
91
+ item_id: ID of the item to delete
92
+
93
+ Returns:
94
+ True if the item was deleted, False if not found
95
+ """
96
+ db_item = get_item(db, item_id)
97
+ if not db_item:
98
+ return False
99
+
100
+ db.delete(db_item)
101
+ db.commit()
102
+ return True
@@ -1,45 +1,45 @@
1
- # --------------------------------------------------------------------------
2
- # Main server application module
3
- # --------------------------------------------------------------------------
4
- from contextlib import asynccontextmanager
5
-
6
- from fastapi import FastAPI
7
- from starlette.middleware.cors import CORSMiddleware
8
-
9
- from src.api.api import api_router
10
- from src.core.config import settings
11
- from src.core.db import create_db_and_tables
12
-
13
-
14
- @asynccontextmanager
15
- async def lifespan(app: FastAPI):
16
- """
17
- Application lifespan manager for startup and shutdown events.
18
-
19
- Creates database tables on startup.
20
- """
21
- # Create tables on startup (in development only)
22
- if settings.ENVIRONMENT == "development":
23
- create_db_and_tables()
24
- yield
25
- # Clean up resources on shutdown if needed
26
-
27
-
28
- app = FastAPI(
29
- title=settings.PROJECT_NAME,
30
- lifespan=lifespan,
31
- description="A simple Item CRUD API demonstrating FastAPI with SQLModel and PostgreSQL",
32
- version="0.1.0",
33
- )
34
-
35
- if settings.all_cors_origins:
36
- app.add_middleware(
37
- CORSMiddleware,
38
- allow_origins=settings.all_cors_origins,
39
- allow_credentials=True,
40
- allow_methods=["*"],
41
- allow_headers=["*"],
42
- )
43
-
44
-
45
- app.include_router(api_router)
1
+ # --------------------------------------------------------------------------
2
+ # Main server application module
3
+ # --------------------------------------------------------------------------
4
+ from contextlib import asynccontextmanager
5
+
6
+ from fastapi import FastAPI
7
+ from starlette.middleware.cors import CORSMiddleware
8
+
9
+ from src.api.api import api_router
10
+ from src.core.config import settings
11
+ from src.core.db import create_db_and_tables
12
+
13
+
14
+ @asynccontextmanager
15
+ async def lifespan(app: FastAPI):
16
+ """
17
+ Application lifespan manager for startup and shutdown events.
18
+
19
+ Creates database tables on startup.
20
+ """
21
+ # Create tables on startup (in development only)
22
+ if settings.ENVIRONMENT == "development":
23
+ create_db_and_tables()
24
+ yield
25
+ # Clean up resources on shutdown if needed
26
+
27
+
28
+ app = FastAPI(
29
+ title=settings.PROJECT_NAME,
30
+ lifespan=lifespan,
31
+ description="A simple Item CRUD API demonstrating FastAPI with SQLModel and PostgreSQL",
32
+ version="0.1.0",
33
+ )
34
+
35
+ if settings.all_cors_origins:
36
+ app.add_middleware(
37
+ CORSMiddleware,
38
+ allow_origins=settings.all_cors_origins,
39
+ allow_credentials=True,
40
+ allow_methods=["*"],
41
+ allow_headers=["*"],
42
+ )
43
+
44
+
45
+ app.include_router(api_router)