fastapi-toolsets 0.1.0__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.
- fastapi_toolsets/__init__.py +24 -0
- fastapi_toolsets/cli/__init__.py +5 -0
- fastapi_toolsets/cli/app.py +97 -0
- fastapi_toolsets/cli/commands/__init__.py +1 -0
- fastapi_toolsets/cli/commands/fixtures.py +225 -0
- fastapi_toolsets/crud.py +378 -0
- fastapi_toolsets/db.py +175 -0
- fastapi_toolsets/exceptions/__init__.py +19 -0
- fastapi_toolsets/exceptions/exceptions.py +166 -0
- fastapi_toolsets/exceptions/handler.py +169 -0
- fastapi_toolsets/fixtures/__init__.py +17 -0
- fastapi_toolsets/fixtures/fixtures.py +321 -0
- fastapi_toolsets/fixtures/pytest_plugin.py +204 -0
- fastapi_toolsets/py.typed +0 -0
- fastapi_toolsets/schemas.py +116 -0
- fastapi_toolsets-0.1.0.dist-info/METADATA +89 -0
- fastapi_toolsets-0.1.0.dist-info/RECORD +20 -0
- fastapi_toolsets-0.1.0.dist-info/WHEEL +4 -0
- fastapi_toolsets-0.1.0.dist-info/entry_points.txt +3 -0
- fastapi_toolsets-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""FastAPI utilities package.
|
|
2
|
+
|
|
3
|
+
Provides CRUD operations, fixtures, CLI, and standardized API responses
|
|
4
|
+
for FastAPI with async SQLAlchemy and PostgreSQL.
|
|
5
|
+
|
|
6
|
+
Example usage:
|
|
7
|
+
from fastapi import FastAPI, Depends
|
|
8
|
+
from fastapi_toolsets.exceptions import init_exceptions_handlers
|
|
9
|
+
from fastapi_toolsets.crud import CrudFactory
|
|
10
|
+
from fastapi_toolsets.db import create_db_dependency
|
|
11
|
+
from fastapi_toolsets.schemas import Response
|
|
12
|
+
|
|
13
|
+
app = FastAPI()
|
|
14
|
+
init_exceptions_handlers(app)
|
|
15
|
+
|
|
16
|
+
UserCrud = CrudFactory(User)
|
|
17
|
+
|
|
18
|
+
@app.get("/users/{user_id}", response_model=Response[dict])
|
|
19
|
+
async def get_user(user_id: int, session = Depends(get_db)):
|
|
20
|
+
user = await UserCrud.get(session, [User.id == user_id])
|
|
21
|
+
return Response(data={"user": user.username}, message="Success")
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Main CLI application."""
|
|
2
|
+
|
|
3
|
+
import importlib.util
|
|
4
|
+
import sys
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Annotated
|
|
7
|
+
|
|
8
|
+
import typer
|
|
9
|
+
|
|
10
|
+
from .commands import fixtures
|
|
11
|
+
|
|
12
|
+
app = typer.Typer(
|
|
13
|
+
name="fastapi-utils",
|
|
14
|
+
help="CLI utilities for FastAPI projects.",
|
|
15
|
+
no_args_is_help=True,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
# Register built-in commands
|
|
19
|
+
app.add_typer(fixtures.app, name="fixtures")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def register_command(command: typer.Typer, name: str) -> None:
|
|
23
|
+
"""Register a custom command group.
|
|
24
|
+
|
|
25
|
+
Args:
|
|
26
|
+
command: Typer app for the command group
|
|
27
|
+
name: Name for the command group
|
|
28
|
+
|
|
29
|
+
Example:
|
|
30
|
+
# In your project's cli.py:
|
|
31
|
+
import typer
|
|
32
|
+
from fastapi_toolsets.cli import app, register_command
|
|
33
|
+
|
|
34
|
+
my_commands = typer.Typer()
|
|
35
|
+
|
|
36
|
+
@my_commands.command()
|
|
37
|
+
def seed():
|
|
38
|
+
'''Seed the database.'''
|
|
39
|
+
...
|
|
40
|
+
|
|
41
|
+
register_command(my_commands, "db")
|
|
42
|
+
# Now available as: fastapi-utils db seed
|
|
43
|
+
"""
|
|
44
|
+
app.add_typer(command, name=name)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@app.callback()
|
|
48
|
+
def main(
|
|
49
|
+
ctx: typer.Context,
|
|
50
|
+
config: Annotated[
|
|
51
|
+
Path | None,
|
|
52
|
+
typer.Option(
|
|
53
|
+
"--config",
|
|
54
|
+
"-c",
|
|
55
|
+
help="Path to project config file (Python module with fixtures registry).",
|
|
56
|
+
envvar="FASTAPI_TOOLSETS_CONFIG",
|
|
57
|
+
),
|
|
58
|
+
] = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
"""FastAPI utilities CLI."""
|
|
61
|
+
ctx.ensure_object(dict)
|
|
62
|
+
|
|
63
|
+
if config:
|
|
64
|
+
ctx.obj["config_path"] = config
|
|
65
|
+
# Load the config module
|
|
66
|
+
config_module = _load_module_from_path(config)
|
|
67
|
+
ctx.obj["config_module"] = config_module
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _load_module_from_path(path: Path) -> object:
|
|
71
|
+
"""Load a Python module from a file path.
|
|
72
|
+
|
|
73
|
+
Handles both absolute and relative imports by adding the config's
|
|
74
|
+
parent directory to sys.path temporarily.
|
|
75
|
+
"""
|
|
76
|
+
path = path.resolve()
|
|
77
|
+
|
|
78
|
+
# Add the parent directory to sys.path to support relative imports
|
|
79
|
+
parent_dir = str(
|
|
80
|
+
path.parent.parent
|
|
81
|
+
) # Go up two levels (e.g., from app/cli_config.py to project root)
|
|
82
|
+
if parent_dir not in sys.path:
|
|
83
|
+
sys.path.insert(0, parent_dir)
|
|
84
|
+
|
|
85
|
+
# Also add immediate parent for direct module imports
|
|
86
|
+
immediate_parent = str(path.parent)
|
|
87
|
+
if immediate_parent not in sys.path:
|
|
88
|
+
sys.path.insert(0, immediate_parent)
|
|
89
|
+
|
|
90
|
+
spec = importlib.util.spec_from_file_location("config", path)
|
|
91
|
+
if spec is None or spec.loader is None:
|
|
92
|
+
raise typer.BadParameter(f"Cannot load module from {path}")
|
|
93
|
+
|
|
94
|
+
module = importlib.util.module_from_spec(spec)
|
|
95
|
+
sys.modules["config"] = module
|
|
96
|
+
spec.loader.exec_module(module)
|
|
97
|
+
return module
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Built-in CLI commands."""
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
"""Fixture management commands."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
from typing import Annotated
|
|
5
|
+
|
|
6
|
+
import typer
|
|
7
|
+
|
|
8
|
+
from ...fixtures import Context, FixtureRegistry, LoadStrategy, load_fixtures_by_context
|
|
9
|
+
|
|
10
|
+
app = typer.Typer(
|
|
11
|
+
name="fixtures",
|
|
12
|
+
help="Manage database fixtures.",
|
|
13
|
+
no_args_is_help=True,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _get_registry(ctx: typer.Context) -> FixtureRegistry:
|
|
18
|
+
"""Get fixture registry from context."""
|
|
19
|
+
config = ctx.obj.get("config_module") if ctx.obj else None
|
|
20
|
+
if config is None:
|
|
21
|
+
raise typer.BadParameter(
|
|
22
|
+
"No config provided. Use --config to specify a config file with a 'fixtures' registry."
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
registry = getattr(config, "fixtures", None)
|
|
26
|
+
if registry is None:
|
|
27
|
+
raise typer.BadParameter(
|
|
28
|
+
"Config module must have a 'fixtures' attribute (FixtureRegistry instance)."
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
if not isinstance(registry, FixtureRegistry):
|
|
32
|
+
raise typer.BadParameter(
|
|
33
|
+
f"'fixtures' must be a FixtureRegistry instance, got {type(registry).__name__}"
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
return registry
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _get_db_context(ctx: typer.Context):
|
|
40
|
+
"""Get database context manager from config."""
|
|
41
|
+
config = ctx.obj.get("config_module") if ctx.obj else None
|
|
42
|
+
if config is None:
|
|
43
|
+
raise typer.BadParameter("No config provided.")
|
|
44
|
+
|
|
45
|
+
get_db_context = getattr(config, "get_db_context", None)
|
|
46
|
+
if get_db_context is None:
|
|
47
|
+
raise typer.BadParameter("Config module must have a 'get_db_context' function.")
|
|
48
|
+
|
|
49
|
+
return get_db_context
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@app.command("list")
|
|
53
|
+
def list_fixtures(
|
|
54
|
+
ctx: typer.Context,
|
|
55
|
+
context: Annotated[
|
|
56
|
+
str | None,
|
|
57
|
+
typer.Option(
|
|
58
|
+
"--context",
|
|
59
|
+
"-c",
|
|
60
|
+
help="Filter by context (base, production, development, testing).",
|
|
61
|
+
),
|
|
62
|
+
] = None,
|
|
63
|
+
) -> None:
|
|
64
|
+
"""List all registered fixtures."""
|
|
65
|
+
registry = _get_registry(ctx)
|
|
66
|
+
|
|
67
|
+
if context:
|
|
68
|
+
fixtures = registry.get_by_context(context)
|
|
69
|
+
else:
|
|
70
|
+
fixtures = registry.get_all()
|
|
71
|
+
|
|
72
|
+
if not fixtures:
|
|
73
|
+
typer.echo("No fixtures found.")
|
|
74
|
+
return
|
|
75
|
+
|
|
76
|
+
typer.echo(f"\n{'Name':<30} {'Contexts':<30} {'Dependencies'}")
|
|
77
|
+
typer.echo("-" * 80)
|
|
78
|
+
|
|
79
|
+
for fixture in fixtures:
|
|
80
|
+
contexts = ", ".join(fixture.contexts)
|
|
81
|
+
deps = ", ".join(fixture.depends_on) if fixture.depends_on else "-"
|
|
82
|
+
typer.echo(f"{fixture.name:<30} {contexts:<30} {deps}")
|
|
83
|
+
|
|
84
|
+
typer.echo(f"\nTotal: {len(fixtures)} fixture(s)")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@app.command("graph")
|
|
88
|
+
def show_graph(
|
|
89
|
+
ctx: typer.Context,
|
|
90
|
+
fixture_name: Annotated[
|
|
91
|
+
str | None,
|
|
92
|
+
typer.Argument(help="Show dependencies for a specific fixture."),
|
|
93
|
+
] = None,
|
|
94
|
+
) -> None:
|
|
95
|
+
"""Show fixture dependency graph."""
|
|
96
|
+
registry = _get_registry(ctx)
|
|
97
|
+
|
|
98
|
+
if fixture_name:
|
|
99
|
+
try:
|
|
100
|
+
order = registry.resolve_dependencies(fixture_name)
|
|
101
|
+
typer.echo(f"\nDependency chain for '{fixture_name}':\n")
|
|
102
|
+
for i, name in enumerate(order):
|
|
103
|
+
indent = " " * i
|
|
104
|
+
arrow = "└─> " if i > 0 else ""
|
|
105
|
+
typer.echo(f"{indent}{arrow}{name}")
|
|
106
|
+
except KeyError:
|
|
107
|
+
typer.echo(f"Fixture '{fixture_name}' not found.", err=True)
|
|
108
|
+
raise typer.Exit(1)
|
|
109
|
+
else:
|
|
110
|
+
# Show full graph
|
|
111
|
+
fixtures = registry.get_all()
|
|
112
|
+
|
|
113
|
+
typer.echo("\nFixture Dependency Graph:\n")
|
|
114
|
+
for fixture in fixtures:
|
|
115
|
+
deps = (
|
|
116
|
+
f" -> [{', '.join(fixture.depends_on)}]" if fixture.depends_on else ""
|
|
117
|
+
)
|
|
118
|
+
typer.echo(f" {fixture.name}{deps}")
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
@app.command("load")
|
|
122
|
+
def load(
|
|
123
|
+
ctx: typer.Context,
|
|
124
|
+
contexts: Annotated[
|
|
125
|
+
list[str] | None,
|
|
126
|
+
typer.Argument(
|
|
127
|
+
help="Contexts to load (base, production, development, testing)."
|
|
128
|
+
),
|
|
129
|
+
] = None,
|
|
130
|
+
strategy: Annotated[
|
|
131
|
+
str,
|
|
132
|
+
typer.Option(
|
|
133
|
+
"--strategy", "-s", help="Load strategy: merge, insert, skip_existing."
|
|
134
|
+
),
|
|
135
|
+
] = "merge",
|
|
136
|
+
dry_run: Annotated[
|
|
137
|
+
bool,
|
|
138
|
+
typer.Option(
|
|
139
|
+
"--dry-run", "-n", help="Show what would be loaded without loading."
|
|
140
|
+
),
|
|
141
|
+
] = False,
|
|
142
|
+
) -> None:
|
|
143
|
+
"""Load fixtures into the database."""
|
|
144
|
+
registry = _get_registry(ctx)
|
|
145
|
+
get_db_context = _get_db_context(ctx)
|
|
146
|
+
|
|
147
|
+
# Parse contexts
|
|
148
|
+
if contexts:
|
|
149
|
+
context_list = contexts
|
|
150
|
+
else:
|
|
151
|
+
context_list = [Context.BASE]
|
|
152
|
+
|
|
153
|
+
# Parse strategy
|
|
154
|
+
try:
|
|
155
|
+
load_strategy = LoadStrategy(strategy)
|
|
156
|
+
except ValueError:
|
|
157
|
+
typer.echo(
|
|
158
|
+
f"Invalid strategy: {strategy}. Use: merge, insert, skip_existing", err=True
|
|
159
|
+
)
|
|
160
|
+
raise typer.Exit(1)
|
|
161
|
+
|
|
162
|
+
# Resolve what will be loaded
|
|
163
|
+
ordered = registry.resolve_context_dependencies(*context_list)
|
|
164
|
+
|
|
165
|
+
if not ordered:
|
|
166
|
+
typer.echo("No fixtures to load for the specified context(s).")
|
|
167
|
+
return
|
|
168
|
+
|
|
169
|
+
typer.echo(f"\nFixtures to load ({load_strategy.value} strategy):")
|
|
170
|
+
for name in ordered:
|
|
171
|
+
fixture = registry.get(name)
|
|
172
|
+
instances = list(fixture.func())
|
|
173
|
+
model_name = type(instances[0]).__name__ if instances else "?"
|
|
174
|
+
typer.echo(f" - {name}: {len(instances)} {model_name}(s)")
|
|
175
|
+
|
|
176
|
+
if dry_run:
|
|
177
|
+
typer.echo("\n[Dry run - no changes made]")
|
|
178
|
+
return
|
|
179
|
+
|
|
180
|
+
typer.echo("\nLoading...")
|
|
181
|
+
|
|
182
|
+
async def do_load():
|
|
183
|
+
async with get_db_context() as session:
|
|
184
|
+
result = await load_fixtures_by_context(
|
|
185
|
+
session, registry, *context_list, strategy=load_strategy
|
|
186
|
+
)
|
|
187
|
+
return result
|
|
188
|
+
|
|
189
|
+
result = asyncio.run(do_load())
|
|
190
|
+
|
|
191
|
+
total = sum(len(items) for items in result.values())
|
|
192
|
+
typer.echo(f"\nLoaded {total} record(s) successfully.")
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
@app.command("show")
|
|
196
|
+
def show_fixture(
|
|
197
|
+
ctx: typer.Context,
|
|
198
|
+
name: Annotated[str, typer.Argument(help="Fixture name to show.")],
|
|
199
|
+
) -> None:
|
|
200
|
+
"""Show details of a specific fixture."""
|
|
201
|
+
registry = _get_registry(ctx)
|
|
202
|
+
|
|
203
|
+
try:
|
|
204
|
+
fixture = registry.get(name)
|
|
205
|
+
except KeyError:
|
|
206
|
+
typer.echo(f"Fixture '{name}' not found.", err=True)
|
|
207
|
+
raise typer.Exit(1)
|
|
208
|
+
|
|
209
|
+
typer.echo(f"\nFixture: {fixture.name}")
|
|
210
|
+
typer.echo(f"Contexts: {', '.join(fixture.contexts)}")
|
|
211
|
+
typer.echo(
|
|
212
|
+
f"Dependencies: {', '.join(fixture.depends_on) if fixture.depends_on else 'None'}"
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
# Show instances
|
|
216
|
+
instances = list(fixture.func())
|
|
217
|
+
if instances:
|
|
218
|
+
model_name = type(instances[0]).__name__
|
|
219
|
+
typer.echo(f"\nInstances ({len(instances)} {model_name}):")
|
|
220
|
+
for instance in instances[:10]: # Limit to 10
|
|
221
|
+
typer.echo(f" - {instance!r}")
|
|
222
|
+
if len(instances) > 10:
|
|
223
|
+
typer.echo(f" ... and {len(instances) - 10} more")
|
|
224
|
+
else:
|
|
225
|
+
typer.echo("\nNo instances (empty fixture)")
|