neurocad-dev 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.
- neurocad_dev/__init__.py +7 -0
- neurocad_dev/app.py +10 -0
- neurocad_dev/cli.py +133 -0
- neurocad_dev/core/module.py +14 -0
- neurocad_dev/core/registry.py +24 -0
- neurocad_dev/core/template.py +40 -0
- neurocad_dev/db/base.py +28 -0
- neurocad_dev/db/mysql.py +62 -0
- neurocad_dev/db/session.py +47 -0
- neurocad_dev/db/sqlite.py +58 -0
- neurocad_dev/py.typed +0 -0
- neurocad_dev/templates/__init__.py +14 -0
- neurocad_dev/templates/project/Makefile +47 -0
- neurocad_dev/templates/project/README.md +109 -0
- neurocad_dev/templates/project/__dot__gitignore +20 -0
- neurocad_dev/templates/project/back/__dot__env.example +20 -0
- neurocad_dev/templates/project/back/__dot__gitignore +17 -0
- neurocad_dev/templates/project/back/alembic/README +20 -0
- neurocad_dev/templates/project/back/alembic/env.py +167 -0
- neurocad_dev/templates/project/back/alembic/script.py.mako +28 -0
- neurocad_dev/templates/project/back/alembic/versions/.gitkeep +0 -0
- neurocad_dev/templates/project/back/alembic.ini__dot__ +66 -0
- neurocad_dev/templates/project/back/app/__init__.py +1 -0
- neurocad_dev/templates/project/back/app/core/__init__.py +6 -0
- neurocad_dev/templates/project/back/app/core/health/__init__.py +5 -0
- neurocad_dev/templates/project/back/app/core/health/models.py +17 -0
- neurocad_dev/templates/project/back/app/core/health/router.py +12 -0
- neurocad_dev/templates/project/back/app/core/health/schemas.py +7 -0
- neurocad_dev/templates/project/back/app/core/health/service.py +10 -0
- neurocad_dev/templates/project/back/app/main.py +53 -0
- neurocad_dev/templates/project/back/app/utils/__init__.py +5 -0
- neurocad_dev/templates/project/back/app/utils/config.py +29 -0
- neurocad_dev/templates/project/back/app/utils/db.py +58 -0
- neurocad_dev/templates/project/back/app/utils/exceptions.py +44 -0
- neurocad_dev/templates/project/back/app/utils/logging.py +11 -0
- neurocad_dev/templates/project/back/app/utils/models.py +14 -0
- neurocad_dev/templates/project/back/app/utils/routes.py +69 -0
- neurocad_dev/templates/project/back/app/utils/security.py +70 -0
- neurocad_dev/templates/project/back/pyproject.toml +25 -0
- neurocad_dev/templates/project/back/tests/test_health.py +45 -0
- neurocad_dev/templates/project/back/tests/test_migrations.py +67 -0
- neurocad_dev/templates/project/deploy/backend.env.example +16 -0
- neurocad_dev/templates/project/deploy/frontend.env.example +6 -0
- neurocad_dev/templates/project/deploy/nginx/{{project_name}}.conf +52 -0
- neurocad_dev/templates/project/deploy/scripts/backup.sh +17 -0
- neurocad_dev/templates/project/deploy/scripts/deploy.sh +67 -0
- neurocad_dev/templates/project/deploy/scripts/install.sh +55 -0
- neurocad_dev/templates/project/deploy/scripts/migrate.sh +23 -0
- neurocad_dev/templates/project/deploy/systemd/{{project_name}}-backend.service +27 -0
- neurocad_dev/templates/project/front/__dot__env.example +3 -0
- neurocad_dev/templates/project/front/__dot__gitignore +4 -0
- neurocad_dev/templates/project/front/index.html +12 -0
- neurocad_dev/templates/project/front/package.json +26 -0
- neurocad_dev/templates/project/front/scripts/genTypes.mjs +56 -0
- neurocad_dev/templates/project/front/src/App.tsx +51 -0
- neurocad_dev/templates/project/front/src/core/health/api.ts +8 -0
- neurocad_dev/templates/project/front/src/core/health/components/HealthWidget.tsx +10 -0
- neurocad_dev/templates/project/front/src/core/health/components/StatusBadge.tsx +24 -0
- neurocad_dev/templates/project/front/src/core/health/hooks.ts +44 -0
- neurocad_dev/templates/project/front/src/core/health/index.tsx +13 -0
- neurocad_dev/templates/project/front/src/core/health/pages/HealthPage.tsx +28 -0
- neurocad_dev/templates/project/front/src/core/health/types.ts +5 -0
- neurocad_dev/templates/project/front/src/env.d.ts +9 -0
- neurocad_dev/templates/project/front/src/main.tsx +13 -0
- neurocad_dev/templates/project/front/src/shared/components/Button.tsx +30 -0
- neurocad_dev/templates/project/front/src/shared/components/Card.tsx +23 -0
- neurocad_dev/templates/project/front/src/shared/layout/Header.tsx +36 -0
- neurocad_dev/templates/project/front/src/shared/layout/Page.tsx +5 -0
- neurocad_dev/templates/project/front/src/utils/apiClient.ts +124 -0
- neurocad_dev/templates/project/front/src/utils/auth.ts +12 -0
- neurocad_dev/templates/project/front/src/utils/config.ts +17 -0
- neurocad_dev/templates/project/front/src/utils/router.tsx +10 -0
- neurocad_dev/templates/project/front/tsconfig.json +24 -0
- neurocad_dev/templates/project/front/vite.config.ts +24 -0
- neurocad_dev/utils/config.py +12 -0
- neurocad_dev/utils/cors.py +42 -0
- neurocad_dev/utils/crypto.py +68 -0
- neurocad_dev/utils/lifespan.py +42 -0
- neurocad_dev/utils/logging.py +23 -0
- neurocad_dev/utils/security.py +137 -0
- neurocad_dev/utils/template_render.py +194 -0
- neurocad_dev/utils/testing.py +143 -0
- neurocad_dev/version.py +1 -0
- neurocad_dev-0.1.0.dist-info/METADATA +296 -0
- neurocad_dev-0.1.0.dist-info/RECORD +88 -0
- neurocad_dev-0.1.0.dist-info/WHEEL +4 -0
- neurocad_dev-0.1.0.dist-info/entry_points.txt +2 -0
- neurocad_dev-0.1.0.dist-info/licenses/LICENSE +21 -0
neurocad_dev/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
from neurocad_dev.version import __version__
|
|
2
|
+
from neurocad_dev.app import create_app
|
|
3
|
+
from neurocad_dev.core.registry import App
|
|
4
|
+
from neurocad_dev.core.module import Module
|
|
5
|
+
from neurocad_dev.utils.config import Settings
|
|
6
|
+
|
|
7
|
+
__all__ = ["create_app", "App", "Module", "Settings", "__version__"]
|
neurocad_dev/app.py
ADDED
neurocad_dev/cli.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Command line entry point: ``neurocad-dev <command>``.
|
|
2
|
+
|
|
3
|
+
Commands
|
|
4
|
+
--------
|
|
5
|
+
``init <path> [--title TITLE] [--name NAME] [--host HOST] [--force]``
|
|
6
|
+
Render the packaged project template into ``<path>``.
|
|
7
|
+
|
|
8
|
+
The template ships inside the wheel (``neurocad_dev/templates/project``), so a
|
|
9
|
+
plain ``pip install neurocad-dev`` is enough: no repository checkout needed.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import re
|
|
16
|
+
import sys
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from neurocad_dev.utils.template_render import (
|
|
20
|
+
TemplateError,
|
|
21
|
+
packaged_templates_dir,
|
|
22
|
+
render_package_template,
|
|
23
|
+
)
|
|
24
|
+
from neurocad_dev.version import __version__
|
|
25
|
+
|
|
26
|
+
__all__ = ["main", "build_context", "slugify"]
|
|
27
|
+
|
|
28
|
+
_NAME_RE = re.compile(r"^[a-z][a-z0-9_]*$")
|
|
29
|
+
_MODULE_RE = re.compile(r"^[a-z][a-z0-9_]*$")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def slugify(value: str) -> str:
|
|
33
|
+
"""``My Great App`` -> ``my_great_app`` (for app_module / project_name)."""
|
|
34
|
+
slug = re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_")
|
|
35
|
+
slug = re.sub(r"_+", "_", slug)
|
|
36
|
+
return slug or "app"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def build_context(
|
|
40
|
+
project_name: str,
|
|
41
|
+
*,
|
|
42
|
+
title: str | None = None,
|
|
43
|
+
host: str = "localhost",
|
|
44
|
+
app_module: str = "app",
|
|
45
|
+
) -> dict[str, str]:
|
|
46
|
+
"""Validate user input and produce the template placeholder mapping."""
|
|
47
|
+
if not _NAME_RE.match(project_name):
|
|
48
|
+
raise ValueError(
|
|
49
|
+
f"invalid project name {project_name!r}: use [a-z][a-z0-9_]* "
|
|
50
|
+
"(it becomes a systemd unit, /opt/<name> and /etc/<name>)"
|
|
51
|
+
)
|
|
52
|
+
if not _MODULE_RE.match(app_module):
|
|
53
|
+
raise ValueError(f"invalid app module {app_module!r}: use [a-z][a-z0-9_]*")
|
|
54
|
+
return {
|
|
55
|
+
"project_name": project_name,
|
|
56
|
+
"project_title": title or project_name.replace("_", " ").title(),
|
|
57
|
+
"project_host": host,
|
|
58
|
+
"app_module": app_module,
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _cmd_init(args: argparse.Namespace) -> int:
|
|
63
|
+
target = Path(args.path).expanduser().resolve()
|
|
64
|
+
if target.exists() and any(target.iterdir()) and not args.force:
|
|
65
|
+
print(
|
|
66
|
+
f"refusing to write into non-empty {target} (use --force)",
|
|
67
|
+
file=sys.stderr,
|
|
68
|
+
)
|
|
69
|
+
return 1
|
|
70
|
+
|
|
71
|
+
try:
|
|
72
|
+
context = build_context(
|
|
73
|
+
args.name or slugify(target.name),
|
|
74
|
+
title=args.title,
|
|
75
|
+
host=args.host,
|
|
76
|
+
app_module=args.app_module,
|
|
77
|
+
)
|
|
78
|
+
written = render_package_template(context, target, name=args.template, force=args.force)
|
|
79
|
+
except (TemplateError, ValueError) as exc:
|
|
80
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
81
|
+
return 1
|
|
82
|
+
|
|
83
|
+
shown = sorted(p.relative_to(target).as_posix() for p in written)
|
|
84
|
+
print(f"Created {len(shown)} files in {target}")
|
|
85
|
+
print(f" project: {context['project_name']} host: {context['project_host']}")
|
|
86
|
+
print()
|
|
87
|
+
print("Next steps:")
|
|
88
|
+
print(f" cd {target}")
|
|
89
|
+
print(" cp back/.env.example back/.env # set SECRET_KEY")
|
|
90
|
+
print(" make install && make dev-back # http://127.0.0.1:8000/docs")
|
|
91
|
+
print(" make dev-front # http://127.0.0.1:5173")
|
|
92
|
+
return 0
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _cmd_templates(_: argparse.Namespace) -> int:
|
|
96
|
+
root = packaged_templates_dir()
|
|
97
|
+
names = sorted(p.name for p in root.iterdir() if p.is_dir())
|
|
98
|
+
for name in names:
|
|
99
|
+
print(name)
|
|
100
|
+
return 0
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
104
|
+
parser = argparse.ArgumentParser(
|
|
105
|
+
prog="neurocad-dev",
|
|
106
|
+
description="NeuroCad scaffold: create and manage modular FastAPI apps.",
|
|
107
|
+
)
|
|
108
|
+
parser.add_argument("--version", action="version", version=f"neurocad-dev {__version__}")
|
|
109
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
110
|
+
|
|
111
|
+
init = sub.add_parser("init", help="create a new project from a template")
|
|
112
|
+
init.add_argument("path", help="target directory")
|
|
113
|
+
init.add_argument("--title", help="human readable title (defaults from path)")
|
|
114
|
+
init.add_argument("--name", help="project name for /opt, /etc, systemd (default: from path)")
|
|
115
|
+
init.add_argument("--host", default="localhost", help="production host for nginx")
|
|
116
|
+
init.add_argument("--app-module", default="app", help="Python package name of the backend")
|
|
117
|
+
init.add_argument("--template", default="project", help="template name (default: project)")
|
|
118
|
+
init.add_argument("--force", action="store_true", help="overwrite existing files")
|
|
119
|
+
init.set_defaults(func=_cmd_init)
|
|
120
|
+
|
|
121
|
+
templates = sub.add_parser("templates", help="list available templates")
|
|
122
|
+
templates.set_defaults(func=_cmd_templates)
|
|
123
|
+
return parser
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def main(argv: list[str] | None = None) -> int:
|
|
127
|
+
parser = build_parser()
|
|
128
|
+
args = parser.parse_args(argv)
|
|
129
|
+
return int(args.func(args))
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
if __name__ == "__main__":
|
|
133
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from fastapi import APIRouter
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass
|
|
9
|
+
class Module:
|
|
10
|
+
"""A self-contained piece of an application: router + mount prefix."""
|
|
11
|
+
|
|
12
|
+
name: str
|
|
13
|
+
router: APIRouter
|
|
14
|
+
prefix: str = ""
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
from fastapi import FastAPI
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from neurocad_dev.core.module import Module
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class App(FastAPI):
|
|
12
|
+
def __init__(self, **kwargs) -> None:
|
|
13
|
+
super().__init__(**kwargs)
|
|
14
|
+
self._modules: dict[str, Module] = {}
|
|
15
|
+
|
|
16
|
+
def include_module(self, module: Module) -> None:
|
|
17
|
+
if module.name in self._modules:
|
|
18
|
+
raise ValueError(f"Module '{module.name}' already registered")
|
|
19
|
+
self._modules[module.name] = module
|
|
20
|
+
self.include_router(module.router, prefix=module.prefix)
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def modules(self) -> dict[str, Module]:
|
|
24
|
+
return dict(self._modules)
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Project templates: in-package file sets rendered into a new project.
|
|
2
|
+
|
|
3
|
+
A :class:`Template` is a named tree of :class:`TemplateFile` entries. The
|
|
4
|
+
engine that turns a template into files on disk lives in
|
|
5
|
+
:mod:`neurocad_dev.utils.template_render`; the CLI in
|
|
6
|
+
:mod:`neurocad_dev.cli`.
|
|
7
|
+
|
|
8
|
+
Templates are static data — no logic, no side effects at import.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class TemplateFile:
|
|
18
|
+
"""One file of a template.
|
|
19
|
+
|
|
20
|
+
``path`` is relative to the project root and may contain
|
|
21
|
+
``{{ placeholders }}``. ``content`` is rendered with the same
|
|
22
|
+
placeholders. ``executable`` sets the +x bit after writing.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
path: str
|
|
26
|
+
content: str
|
|
27
|
+
executable: bool = False
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Template:
|
|
32
|
+
"""A named set of files, e.g. the full ``back + front + deploy`` project."""
|
|
33
|
+
|
|
34
|
+
name: str
|
|
35
|
+
description: str = ""
|
|
36
|
+
files: tuple[TemplateFile, ...] = field(default_factory=tuple)
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def paths(self) -> tuple[str, ...]:
|
|
40
|
+
return tuple(f.path for f in self.files)
|
neurocad_dev/db/base.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from datetime import UTC, datetime
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import DateTime, func
|
|
6
|
+
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Base(DeclarativeBase):
|
|
10
|
+
"""Declarative base for application models."""
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class TimestampMixin:
|
|
14
|
+
"""Adds ``created_at`` / ``updated_at`` columns."""
|
|
15
|
+
|
|
16
|
+
created_at: Mapped[datetime] = mapped_column(
|
|
17
|
+
DateTime(timezone=True),
|
|
18
|
+
default=lambda: datetime.now(UTC),
|
|
19
|
+
server_default=func.now(),
|
|
20
|
+
nullable=False,
|
|
21
|
+
)
|
|
22
|
+
updated_at: Mapped[datetime] = mapped_column(
|
|
23
|
+
DateTime(timezone=True),
|
|
24
|
+
default=lambda: datetime.now(UTC),
|
|
25
|
+
server_default=func.now(),
|
|
26
|
+
onupdate=lambda: datetime.now(UTC),
|
|
27
|
+
nullable=False,
|
|
28
|
+
)
|
neurocad_dev/db/mysql.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncIterator
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import text
|
|
6
|
+
from sqlalchemy.ext.asyncio import (
|
|
7
|
+
AsyncEngine,
|
|
8
|
+
AsyncSession,
|
|
9
|
+
async_sessionmaker,
|
|
10
|
+
create_async_engine,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
#: MySQL is optional: the engine is created lazily on the first ``init_mysql()``
|
|
14
|
+
#: call, so importing this module never opens a connection.
|
|
15
|
+
engine: AsyncEngine | None = None
|
|
16
|
+
SessionLocal: async_sessionmaker[AsyncSession] | None = None
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
async def init_mysql(url: str) -> AsyncEngine:
|
|
20
|
+
"""Create (once) and verify the MySQL engine for ``url``.
|
|
21
|
+
|
|
22
|
+
Expects an async driver URL, e.g.
|
|
23
|
+
``mysql+asyncmy://user:password@host:3306/db``.
|
|
24
|
+
"""
|
|
25
|
+
global engine, SessionLocal
|
|
26
|
+
|
|
27
|
+
if engine is None:
|
|
28
|
+
engine = create_async_engine(
|
|
29
|
+
url,
|
|
30
|
+
pool_size=10,
|
|
31
|
+
max_overflow=20,
|
|
32
|
+
pool_pre_ping=True,
|
|
33
|
+
)
|
|
34
|
+
SessionLocal = async_sessionmaker(
|
|
35
|
+
engine,
|
|
36
|
+
class_=AsyncSession,
|
|
37
|
+
expire_on_commit=False,
|
|
38
|
+
autoflush=False,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
async with engine.connect() as conn:
|
|
42
|
+
await conn.execute(text("SELECT 1"))
|
|
43
|
+
|
|
44
|
+
return engine
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
async def close_mysql() -> None:
|
|
48
|
+
"""Dispose the MySQL engine, if it was created."""
|
|
49
|
+
global engine, SessionLocal
|
|
50
|
+
|
|
51
|
+
if engine is not None:
|
|
52
|
+
await engine.dispose()
|
|
53
|
+
engine = None
|
|
54
|
+
SessionLocal = None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
async def get_db_mysql() -> AsyncIterator[AsyncSession]:
|
|
58
|
+
"""Session generator for MySQL. Requires a prior ``init_mysql()``."""
|
|
59
|
+
if SessionLocal is None:
|
|
60
|
+
raise RuntimeError("MySQL is not initialised — call init_mysql() first")
|
|
61
|
+
async with SessionLocal() as session:
|
|
62
|
+
yield session
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from collections.abc import AsyncIterator
|
|
5
|
+
from typing import Annotated
|
|
6
|
+
|
|
7
|
+
from fastapi import Depends
|
|
8
|
+
from sqlalchemy.ext.asyncio import (
|
|
9
|
+
AsyncEngine,
|
|
10
|
+
AsyncSession,
|
|
11
|
+
async_sessionmaker,
|
|
12
|
+
create_async_engine,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
_DEFAULT_SQLITE_URL = "sqlite+aiosqlite:///./app.db"
|
|
16
|
+
|
|
17
|
+
DATABASE_URL: str = os.getenv("DATABASE_URL", "") or _DEFAULT_SQLITE_URL
|
|
18
|
+
IS_SQLITE: bool = DATABASE_URL.startswith("sqlite")
|
|
19
|
+
|
|
20
|
+
engine: AsyncEngine = create_async_engine(
|
|
21
|
+
DATABASE_URL,
|
|
22
|
+
pool_pre_ping=True,
|
|
23
|
+
echo=False,
|
|
24
|
+
# SQLite's async adapter wants check_same_thread=False.
|
|
25
|
+
connect_args={"check_same_thread": False} if IS_SQLITE else {},
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
if IS_SQLITE:
|
|
29
|
+
from neurocad_dev.db.sqlite import apply_sqlite_pragmas
|
|
30
|
+
|
|
31
|
+
apply_sqlite_pragmas(engine)
|
|
32
|
+
|
|
33
|
+
SessionLocal = async_sessionmaker(
|
|
34
|
+
engine,
|
|
35
|
+
class_=AsyncSession,
|
|
36
|
+
expire_on_commit=False,
|
|
37
|
+
autoflush=False,
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
async def get_session() -> AsyncIterator[AsyncSession]:
|
|
42
|
+
"""FastAPI dependency yielding an ``AsyncSession``."""
|
|
43
|
+
async with SessionLocal() as session:
|
|
44
|
+
yield session
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
DB = Annotated[AsyncSession, Depends(get_session)]
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import AsyncIterator
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import event, text
|
|
6
|
+
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
|
|
7
|
+
|
|
8
|
+
#: PRAGMAs applied to every new SQLite connection.
|
|
9
|
+
#:
|
|
10
|
+
#: WAL — writers do not block readers (relevant for async apps that mix
|
|
11
|
+
#: HTTP saves with websocket/long-running work).
|
|
12
|
+
#: synchronous=NORMAL — safe under WAL, faster than FULL.
|
|
13
|
+
#: busy_timeout=30000 — wait up to 30 s on a locked DB instead of failing.
|
|
14
|
+
#: foreign_keys=ON — SQLite does not enforce foreign keys by default.
|
|
15
|
+
SQLITE_PRAGMAS: tuple[str, ...] = (
|
|
16
|
+
"PRAGMA journal_mode=WAL",
|
|
17
|
+
"PRAGMA synchronous=NORMAL",
|
|
18
|
+
"PRAGMA busy_timeout=30000",
|
|
19
|
+
"PRAGMA foreign_keys=ON",
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def apply_sqlite_pragmas(engine: AsyncEngine) -> None:
|
|
24
|
+
"""Register the PRAGMA hook on an async SQLite engine (sync_engine level)."""
|
|
25
|
+
|
|
26
|
+
@event.listens_for(engine.sync_engine, "connect")
|
|
27
|
+
def _set_sqlite_pragma(dbapi_connection, connection_record) -> None: # noqa: ANN001
|
|
28
|
+
cursor = dbapi_connection.cursor()
|
|
29
|
+
try:
|
|
30
|
+
for pragma in SQLITE_PRAGMAS:
|
|
31
|
+
cursor.execute(pragma)
|
|
32
|
+
finally:
|
|
33
|
+
cursor.close()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def make_session_factory(engine: AsyncEngine) -> async_sessionmaker[AsyncSession]:
|
|
37
|
+
"""Build a session factory with the project-wide defaults."""
|
|
38
|
+
return async_sessionmaker(
|
|
39
|
+
engine,
|
|
40
|
+
class_=AsyncSession,
|
|
41
|
+
expire_on_commit=False,
|
|
42
|
+
autoflush=False,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def get_db_sqlite(
|
|
47
|
+
session_factory: async_sessionmaker[AsyncSession],
|
|
48
|
+
) -> AsyncIterator[AsyncSession]:
|
|
49
|
+
"""Session generator for an explicitly provided SQLite factory."""
|
|
50
|
+
async with session_factory() as session:
|
|
51
|
+
yield session
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
async def ping(engine: AsyncEngine) -> bool:
|
|
55
|
+
"""Check that the engine can reach the database."""
|
|
56
|
+
async with engine.connect() as conn:
|
|
57
|
+
result = await conn.execute(text("SELECT 1"))
|
|
58
|
+
return result.scalar_one() == 1
|
neurocad_dev/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Project templates shipped inside the package.
|
|
2
|
+
|
|
3
|
+
``templates/project/`` is the full ``back + front + deploy`` skeleton
|
|
4
|
+
(Part 2 of the spec). It is rendered into a new directory by
|
|
5
|
+
``neurocad-dev init <path>``.
|
|
6
|
+
|
|
7
|
+
Dotfiles are stored with the ``__dot__`` prefix so build tools cannot
|
|
8
|
+
strip them: ``__dot__gitignore`` -> ``.gitignore``,
|
|
9
|
+
``__dot__env.example`` -> ``.env.example``. The renderer restores the real
|
|
10
|
+
names (see `neurocad_dev.utils.template_render`).
|
|
11
|
+
|
|
12
|
+
This module is not imported by ``neurocad_dev/__init__.py`` — the package
|
|
13
|
+
stays free of import side effects.
|
|
14
|
+
"""
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# {{project_title}} — dev workflow
|
|
2
|
+
#
|
|
3
|
+
# make install — backend venv + frontend node_modules
|
|
4
|
+
# make dev-back — uvicorn --reload (http://127.0.0.1:8000/docs)
|
|
5
|
+
# make dev-front — vite (http://127.0.0.1:5173)
|
|
6
|
+
# make test — pytest + tsc
|
|
7
|
+
# make types — regenerate module types.ts from OpenAPI (backend must run)
|
|
8
|
+
# make build — backend wheel + frontend dist
|
|
9
|
+
# make clean
|
|
10
|
+
|
|
11
|
+
SHELL := /bin/bash
|
|
12
|
+
BACK := back
|
|
13
|
+
FRONT := front
|
|
14
|
+
|
|
15
|
+
.PHONY: help install dev-back dev-front test types build clean
|
|
16
|
+
|
|
17
|
+
help:
|
|
18
|
+
@grep -E '^# ' Makefile | sed 's/^# //'
|
|
19
|
+
|
|
20
|
+
install:
|
|
21
|
+
python3 -m venv $(BACK)/.venv
|
|
22
|
+
$(BACK)/.venv/bin/pip install --upgrade pip
|
|
23
|
+
$(BACK)/.venv/bin/pip install -e "$(BACK)[dev]"
|
|
24
|
+
cd $(FRONT) && npm install
|
|
25
|
+
|
|
26
|
+
dev-back:
|
|
27
|
+
cd $(BACK) && .venv/bin/uvicorn app.main:app --reload --host 127.0.0.1 --port 8000
|
|
28
|
+
|
|
29
|
+
dev-front:
|
|
30
|
+
cd $(FRONT) && npm run dev
|
|
31
|
+
|
|
32
|
+
test:
|
|
33
|
+
cd $(BACK) && .venv/bin/python -m pytest -q
|
|
34
|
+
cd $(FRONT) && npm run typecheck
|
|
35
|
+
|
|
36
|
+
types:
|
|
37
|
+
cd $(FRONT) && npm run gen:types
|
|
38
|
+
|
|
39
|
+
build:
|
|
40
|
+
$(BACK)/.venv/bin/pip install --quiet build
|
|
41
|
+
cd $(BACK) && .venv/bin/python -m build
|
|
42
|
+
cd $(FRONT) && npm run build
|
|
43
|
+
|
|
44
|
+
clean:
|
|
45
|
+
rm -rf $(BACK)/dist $(BACK)/build $(FRONT)/dist
|
|
46
|
+
find . -name '__pycache__' -type d -prune -exec rm -rf {} +
|
|
47
|
+
rm -rf $(BACK)/.pytest_cache
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# {{project_title}}
|
|
2
|
+
|
|
3
|
+
Generated by `neurocad-dev init` — a modular full-stack skeleton on top of
|
|
4
|
+
[neurocad-dev](https://pypi.org/project/neurocad-dev/) and FastAPI.
|
|
5
|
+
|
|
6
|
+
## Layout
|
|
7
|
+
|
|
8
|
+
```
|
|
9
|
+
back/ FastAPI + neurocad-dev (async SQLAlchemy)
|
|
10
|
+
alembic/ migrations, versions/<year>/<month>/<day>/
|
|
11
|
+
.alembic.ini alembic config (per-project file name)
|
|
12
|
+
app/main.py create_app() + lifespan + auto-discovery
|
|
13
|
+
app/utils/ config, security, logging, exceptions, db, models, routes
|
|
14
|
+
app/core/<module>/ business modules (flat, unique names)
|
|
15
|
+
front/ React + Vite + TypeScript
|
|
16
|
+
src/core/<module>/ mirrors back/app/core/<module> (same names)
|
|
17
|
+
src/shared/ UI primitives (components/, layout/)
|
|
18
|
+
src/utils/ apiClient, config, auth, router (explicit list)
|
|
19
|
+
deploy/ systemd/nginx units (source of truth), scripts
|
|
20
|
+
(install/deploy/migrate/backup)
|
|
21
|
+
Makefile
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## Conventions
|
|
25
|
+
|
|
26
|
+
* **Modules are bricks**: `back/app/core/users/` ↔ `front/src/core/users/`.
|
|
27
|
+
* **API prefix == module directory name**: `core/users` → `/users`.
|
|
28
|
+
* A backend module exports `router` from `__init__.py`; `app/utils/routes.py`
|
|
29
|
+
discovers `app/core/*` in alphabetical order and fails fast on mistakes.
|
|
30
|
+
* A frontend module exposes `...Routes` from `index.ts`/`index.tsx`;
|
|
31
|
+
`utils/router.tsx` lists them explicitly (no glob auto-discovery — Vite
|
|
32
|
+
tree-shaking).
|
|
33
|
+
* `types.ts` is generated: `make types` (backend up) writes OpenAPI types
|
|
34
|
+
sliced by module prefix plus one alias per schema, so module code imports
|
|
35
|
+
`type { HealthResponse }` as usual.
|
|
36
|
+
* Public interfaces: backend `service.py`, frontend `index.ts`. Never reach
|
|
37
|
+
into another module's internals.
|
|
38
|
+
* `utils/` (back) and `shared/` (front) are the framework layer — they never
|
|
39
|
+
import business code; helpers used by one module live in that module.
|
|
40
|
+
* Naming: back `snake_case`, front `camelCase` files, `PascalCase` components,
|
|
41
|
+
`PascalCase` types, `UPPER_SNAKE` constants, `kebab-case` URLs. The
|
|
42
|
+
snake_case ↔ camelCase boundary is handled by `apiClient` + generated types.
|
|
43
|
+
* `.env` = infrastructure + secrets + feature flags (not in git);
|
|
44
|
+
`.env.example` is the documentation (in git).
|
|
45
|
+
* Logs go to journald: `journalctl -u {{project_name}}-backend -f`.
|
|
46
|
+
|
|
47
|
+
## Quick start
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
cp back/.env.example back/.env # set SECRET_KEY
|
|
51
|
+
make install
|
|
52
|
+
make dev-back # http://127.0.0.1:8000/docs
|
|
53
|
+
make dev-front # http://127.0.0.1:5173
|
|
54
|
+
make test
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Add a module in three steps:
|
|
58
|
+
|
|
59
|
+
1. `back/app/core/billing/` with `__init__.py` exporting `router`
|
|
60
|
+
(`APIRouter(prefix="/billing")`), `router.py`, `schemas.py`, `service.py`,
|
|
61
|
+
and `models.py` when the module owns tables.
|
|
62
|
+
2. `front/src/core/billing/` with `api.ts`, `hooks.ts`, and `index.tsx`
|
|
63
|
+
(`export const billingRoutes = [...]`; use `.tsx` when the index builds
|
|
64
|
+
route elements — plain `.ts` for types/data only).
|
|
65
|
+
3. `front/src/utils/router.tsx`: add `...billingRoutes` to `routes`.
|
|
66
|
+
|
|
67
|
+
## Migrations (Alembic)
|
|
68
|
+
|
|
69
|
+
Models subclass `app.utils.models.Base`; `alembic/env.py` imports every
|
|
70
|
+
`app/core/*/models.py` automatically.
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
cd back
|
|
74
|
+
.venv/bin/alembic -c .alembic.ini upgrade head
|
|
75
|
+
.venv/bin/alembic -c .alembic.ini revision --autogenerate -m "add billing"
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Revisions are stored as `alembic/versions/<year>/<month>/<day>/<HHMMSS>_<slug>.py`
|
|
79
|
+
(the day folder is created automatically). The async `DATABASE_URL` is converted
|
|
80
|
+
to a sync driver for Alembic. `alembic revision` runs the `black` post-write
|
|
81
|
+
hook — `pip install black`, or drop `[post_write_hooks]` from `.alembic.ini`.
|
|
82
|
+
|
|
83
|
+
## Production
|
|
84
|
+
|
|
85
|
+
Artifacts live in `/opt/{{project_name}}/{back,front}/releases/<version>`
|
|
86
|
+
with a `current` symlink; `/opt/{{project_name}}/data` is the only state.
|
|
87
|
+
Secrets live in `/etc/{{project_name}}/{backend,frontend}.env` (root:app, 640).
|
|
88
|
+
|
|
89
|
+
**Configs are owned by this repo.** `deploy/systemd/*.service` and
|
|
90
|
+
`deploy/nginx/*.conf` are the source of truth; `install.sh` only links them:
|
|
91
|
+
|
|
92
|
+
```
|
|
93
|
+
/etc/systemd/system/{{project_name}}-backend.service -> <repo>/deploy/systemd/...
|
|
94
|
+
/etc/nginx/sites-available/{{project_name}}.conf -> <repo>/deploy/nginx/...
|
|
95
|
+
/etc/nginx/sites-enabled/{{project_name}}.conf -> sites-available/...
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Edit the files in `deploy/`, then `sudo deploy/scripts/install.sh` re-links and
|
|
99
|
+
reloads (systemd + nginx). The frontend is served by nginx straight from
|
|
100
|
+
`/opt/{{project_name}}/front/current/dist` — no Node process in production.
|
|
101
|
+
|
|
102
|
+
```bash
|
|
103
|
+
sudo deploy/scripts/install.sh # one-time: link + reload
|
|
104
|
+
sudo deploy/scripts/deploy.sh back 0.1.0 /tmp/back-0.1.0
|
|
105
|
+
sudo deploy/scripts/deploy.sh front 0.1.0 /tmp/front-0.1.0
|
|
106
|
+
sudo deploy/scripts/migrate.sh
|
|
107
|
+
sudo deploy/scripts/backup.sh
|
|
108
|
+
sudo deploy/scripts/deploy.sh back rollback 0.0.9 # rollback = repoint symlink
|
|
109
|
+
```
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Application
|
|
2
|
+
APP_TITLE={{project_title}}
|
|
3
|
+
APP_HOST=127.0.0.1
|
|
4
|
+
APP_PORT=8000
|
|
5
|
+
DEBUG=true
|
|
6
|
+
ENV=dev
|
|
7
|
+
|
|
8
|
+
# Secrets (generate: openssl rand -hex 32)
|
|
9
|
+
SECRET_KEY=change-me-please-generate-a-random-32-byte-key
|
|
10
|
+
|
|
11
|
+
# Databases (async drivers)
|
|
12
|
+
DATABASE_URL=sqlite+aiosqlite:///./data/app.db
|
|
13
|
+
# DATABASE_URL=mysql+asyncmy://user:password@127.0.0.1:3306/{{app_module}}
|
|
14
|
+
MYSQL_URL=
|
|
15
|
+
|
|
16
|
+
# Security
|
|
17
|
+
ACCESS_TOKEN_EXPIRE_MINUTES=1440
|
|
18
|
+
|
|
19
|
+
# Frontend (VITE_* are baked in at build time)
|
|
20
|
+
VITE_API_BASE_URL=http://127.0.0.1:8000
|