shaapi 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.
Files changed (141) hide show
  1. shaapi/__init__.py +3 -0
  2. shaapi/cli.py +97 -0
  3. shaapi/generator.py +114 -0
  4. shaapi/template/.dockerignore +37 -0
  5. shaapi/template/.env.template +59 -0
  6. shaapi/template/.gitattributes +12 -0
  7. shaapi/template/.gitignore +170 -0
  8. shaapi/template/.gitlab-ci.yml +89 -0
  9. shaapi/template/Dockerfile +59 -0
  10. shaapi/template/LICENSE +21 -0
  11. shaapi/template/README.md +206 -0
  12. shaapi/template/backend/.gitignore +164 -0
  13. shaapi/template/backend/__init__.py +0 -0
  14. shaapi/template/backend/alembic/README +1 -0
  15. shaapi/template/backend/alembic/env.py +102 -0
  16. shaapi/template/backend/alembic/script.py.mako +26 -0
  17. shaapi/template/backend/alembic/versions/2026_06_08_1024-64524c63b666_initial.py +143 -0
  18. shaapi/template/backend/alembic.ini +117 -0
  19. shaapi/template/backend/app/__init__.py +55 -0
  20. shaapi/template/backend/app/admin/__init__.py +1 -0
  21. shaapi/template/backend/app/admin/api/v1/__init__.py +0 -0
  22. shaapi/template/backend/app/admin/api/v1/auth.py +59 -0
  23. shaapi/template/backend/app/admin/api/v1/casbin.py +218 -0
  24. shaapi/template/backend/app/admin/api/v1/login_log.py +63 -0
  25. shaapi/template/backend/app/admin/api/v1/opera_log.py +61 -0
  26. shaapi/template/backend/app/admin/api/v1/role.py +108 -0
  27. shaapi/template/backend/app/admin/api/v1/user.py +47 -0
  28. shaapi/template/backend/app/admin/schema/casbin_rule.py +45 -0
  29. shaapi/template/backend/app/admin/schema/login_log.py +36 -0
  30. shaapi/template/backend/app/admin/schema/opera_log.py +43 -0
  31. shaapi/template/backend/app/admin/schema/role.py +36 -0
  32. shaapi/template/backend/app/admin/schema/sso.py +37 -0
  33. shaapi/template/backend/app/admin/schema/token.py +74 -0
  34. shaapi/template/backend/app/admin/schema/user.py +93 -0
  35. shaapi/template/backend/app/admin/service/auth_service.py +233 -0
  36. shaapi/template/backend/app/admin/service/casbin_service.py +135 -0
  37. shaapi/template/backend/app/admin/service/login_log_service.py +62 -0
  38. shaapi/template/backend/app/admin/service/opera_log_service.py +31 -0
  39. shaapi/template/backend/app/admin/service/role_service.py +79 -0
  40. shaapi/template/backend/app/admin/service/secure_token_service.py +60 -0
  41. shaapi/template/backend/app/admin/service/user_service.py +153 -0
  42. shaapi/template/backend/app/api.py +11 -0
  43. shaapi/template/backend/common/__init__.py +0 -0
  44. shaapi/template/backend/common/cloud_storage/__init__.py +11 -0
  45. shaapi/template/backend/common/cloud_storage/cloud_storage.py +180 -0
  46. shaapi/template/backend/common/dataclasses.py +52 -0
  47. shaapi/template/backend/common/email_conf/email.py +105 -0
  48. shaapi/template/backend/common/enums.py +144 -0
  49. shaapi/template/backend/common/exception/__init__.py +0 -0
  50. shaapi/template/backend/common/exception/errors.py +87 -0
  51. shaapi/template/backend/common/exception/exception_handler.py +280 -0
  52. shaapi/template/backend/common/log.py +123 -0
  53. shaapi/template/backend/common/model.py +68 -0
  54. shaapi/template/backend/common/pagination.py +83 -0
  55. shaapi/template/backend/common/response/__init__.py +0 -0
  56. shaapi/template/backend/common/response/response_code.py +158 -0
  57. shaapi/template/backend/common/response/response_schema.py +110 -0
  58. shaapi/template/backend/common/schema.py +144 -0
  59. shaapi/template/backend/common/security/jwt.py +203 -0
  60. shaapi/template/backend/common/security/rbac.py +98 -0
  61. shaapi/template/backend/common/security/sec_token.py +6 -0
  62. shaapi/template/backend/common/socketio/action.py +11 -0
  63. shaapi/template/backend/common/socketio/server.py +50 -0
  64. shaapi/template/backend/common/sso/base.py +69 -0
  65. shaapi/template/backend/common/sso/google.py +127 -0
  66. shaapi/template/backend/core/conf.py +208 -0
  67. shaapi/template/backend/core/path_conf.py +24 -0
  68. shaapi/template/backend/core/registrar.py +195 -0
  69. shaapi/template/backend/crud/__init__.py +1 -0
  70. shaapi/template/backend/crud/crud_base.py +35 -0
  71. shaapi/template/backend/crud/crud_casbin.py +46 -0
  72. shaapi/template/backend/crud/crud_login_log.py +58 -0
  73. shaapi/template/backend/crud/crud_opera_log.py +58 -0
  74. shaapi/template/backend/crud/crud_role.py +128 -0
  75. shaapi/template/backend/crud/crud_user.py +267 -0
  76. shaapi/template/backend/database/__init__.py +0 -0
  77. shaapi/template/backend/database/db_postgres.py +125 -0
  78. shaapi/template/backend/database/db_redis.py +62 -0
  79. shaapi/template/backend/entrypoint-api.sh +19 -0
  80. shaapi/template/backend/lang/en/app.py +18 -0
  81. shaapi/template/backend/lang/en/auth.py +10 -0
  82. shaapi/template/backend/lang/fr/app.py +18 -0
  83. shaapi/template/backend/lang/fr/auth.py +10 -0
  84. shaapi/template/backend/main.py +54 -0
  85. shaapi/template/backend/middleware/__init__.py +1 -0
  86. shaapi/template/backend/middleware/access_middleware.py +19 -0
  87. shaapi/template/backend/middleware/i18n_middleware.py +19 -0
  88. shaapi/template/backend/middleware/jwt_auth_middleware.py +73 -0
  89. shaapi/template/backend/middleware/opera_log_middleware.py +179 -0
  90. shaapi/template/backend/middleware/state_middleware.py +26 -0
  91. shaapi/template/backend/models/__init__.py +10 -0
  92. shaapi/template/backend/models/associations.py +20 -0
  93. shaapi/template/backend/models/casbin_rule.py +30 -0
  94. shaapi/template/backend/models/login_log.py +28 -0
  95. shaapi/template/backend/models/opera_log.py +36 -0
  96. shaapi/template/backend/models/role.py +27 -0
  97. shaapi/template/backend/models/user.py +30 -0
  98. shaapi/template/backend/seeder/json/admin.json +15 -0
  99. shaapi/template/backend/seeder/json/user.json +15 -0
  100. shaapi/template/backend/seeder/run.py +34 -0
  101. shaapi/template/backend/static/ip2region.xdb +0 -0
  102. shaapi/template/backend/templates/build/meet.html +169 -0
  103. shaapi/template/backend/templates/build/new_account.html +373 -0
  104. shaapi/template/backend/templates/build/reset-password.html +170 -0
  105. shaapi/template/backend/templates/build/test_email.html +25 -0
  106. shaapi/template/backend/templates/build/welcome-one-1.html +160 -0
  107. shaapi/template/backend/templates/build/welcome-one.html +178 -0
  108. shaapi/template/backend/templates/build/welcome-two.html +234 -0
  109. shaapi/template/backend/templates/index.html +0 -0
  110. shaapi/template/backend/templates/src/new_account.mjml +15 -0
  111. shaapi/template/backend/templates/src/reset_password.mjml +19 -0
  112. shaapi/template/backend/templates/src/test_email.mjml +11 -0
  113. shaapi/template/backend/templates/ws/ws.html +70 -0
  114. shaapi/template/backend/utils/demo_site.py +18 -0
  115. shaapi/template/backend/utils/encrypt.py +108 -0
  116. shaapi/template/backend/utils/health_check.py +34 -0
  117. shaapi/template/backend/utils/prometheus.py +135 -0
  118. shaapi/template/backend/utils/request_parse.py +110 -0
  119. shaapi/template/backend/utils/serializers.py +75 -0
  120. shaapi/template/backend/utils/timezone.py +51 -0
  121. shaapi/template/backend/utils/trace_id.py +7 -0
  122. shaapi/template/backend/utils/translator.py +28 -0
  123. shaapi/template/devops/scripts/deploy.sh +7 -0
  124. shaapi/template/devops/scripts/setup_env.sh +62 -0
  125. shaapi/template/docker-compose.monitoring.yml +63 -0
  126. shaapi/template/docker-compose.override.yml +12 -0
  127. shaapi/template/docker-compose.yml +90 -0
  128. shaapi/template/docker-run.sh +99 -0
  129. shaapi/template/etc/dashboards/fastapi-observability.json +1044 -0
  130. shaapi/template/etc/dashboards.yaml +10 -0
  131. shaapi/template/etc/grafana/datasource.yml +79 -0
  132. shaapi/template/etc/prometheus/prometheus.yml +52 -0
  133. shaapi/template/package-lock.json +2102 -0
  134. shaapi/template/package.json +16 -0
  135. shaapi/template/pyproject.toml +78 -0
  136. shaapi/template/uv.lock +2866 -0
  137. shaapi-0.1.0.dist-info/METADATA +92 -0
  138. shaapi-0.1.0.dist-info/RECORD +141 -0
  139. shaapi-0.1.0.dist-info/WHEEL +4 -0
  140. shaapi-0.1.0.dist-info/entry_points.txt +2 -0
  141. shaapi-0.1.0.dist-info/licenses/LICENCE +21 -0
shaapi/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """shaapi — scaffold lean, batteries-included FastAPI backends."""
2
+
3
+ __version__ = "0.1.0"
shaapi/cli.py ADDED
@@ -0,0 +1,97 @@
1
+ """shaapi command-line interface."""
2
+ from __future__ import annotations
3
+
4
+ import sys
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ import typer
9
+ from rich.console import Console
10
+ from rich.panel import Panel
11
+
12
+ from shaapi import __version__
13
+ from shaapi.generator import create_project, slugify
14
+
15
+ # Make output robust on Windows consoles (cp1252) and when piped.
16
+ for _stream in (sys.stdout, sys.stderr):
17
+ try:
18
+ _stream.reconfigure(encoding="utf-8") # type: ignore[union-attr]
19
+ except (AttributeError, ValueError):
20
+ pass
21
+
22
+ app = typer.Typer(
23
+ add_completion=False,
24
+ no_args_is_help=True,
25
+ help="shaapi - scaffold lean, batteries-included FastAPI backends.",
26
+ )
27
+ console = Console()
28
+
29
+
30
+ @app.command("create-project")
31
+ def create_project_command(
32
+ name: str = typer.Argument(..., help='Project name, e.g. "my api".'),
33
+ path: Path = typer.Option(Path("."), "--path", "-p", help="Where to create the project."),
34
+ monitoring: Optional[bool] = typer.Option(
35
+ None, "--monitoring/--no-monitoring", help="Include the Prometheus/Grafana stack."
36
+ ),
37
+ git: Optional[bool] = typer.Option(
38
+ None, "--git/--no-git", help="Initialize a git repository."
39
+ ),
40
+ yes: bool = typer.Option(False, "--yes", "-y", help="Accept defaults, skip prompts."),
41
+ ):
42
+ """Create a new shaapi project."""
43
+ slug = slugify(name)
44
+ console.print(f"\n[bold cyan]shaapi[/] creating project [bold]{slug}[/]\n")
45
+
46
+ if monitoring is None:
47
+ monitoring = (
48
+ False if yes
49
+ else typer.confirm("Include monitoring (Prometheus/Grafana/Tempo/Loki)?", default=False)
50
+ )
51
+ if git is None:
52
+ git = True if yes else typer.confirm("Initialize a git repository?", default=True)
53
+
54
+ try:
55
+ dest = create_project(name, path, monitoring=monitoring, git_init=git)
56
+ except (FileExistsError, ValueError, RuntimeError) as exc:
57
+ console.print(f"[bold red]Error:[/] {exc}")
58
+ raise typer.Exit(code=1)
59
+
60
+ up_cmd = "./docker-run.sh up" + (" --monitoring" if monitoring else "")
61
+ console.print(
62
+ Panel.fit(
63
+ f"[green][OK][/] Project created at [bold]{dest}[/]\n\n"
64
+ f"[bold]Next steps[/]\n"
65
+ f" cd {dest.name}\n"
66
+ f" {up_cmd}\n\n"
67
+ f"Then open [cyan]http://localhost:8000/admin/api/v1/docs[/]",
68
+ title="Done",
69
+ border_style="cyan",
70
+ )
71
+ )
72
+
73
+
74
+ def _version_callback(value: bool) -> None:
75
+ if value:
76
+ console.print(f"shaapi {__version__}")
77
+ raise typer.Exit()
78
+
79
+
80
+ @app.command()
81
+ def version() -> None:
82
+ """Show the shaapi version."""
83
+ console.print(f"shaapi {__version__}")
84
+
85
+
86
+ @app.callback()
87
+ def main(
88
+ _version: Optional[bool] = typer.Option(
89
+ None, "--version", "-V", callback=_version_callback, is_eager=True,
90
+ help="Show the version and exit.",
91
+ ),
92
+ ) -> None:
93
+ """shaapi CLI."""
94
+
95
+
96
+ if __name__ == "__main__":
97
+ app()
shaapi/generator.py ADDED
@@ -0,0 +1,114 @@
1
+ """Project scaffolding: copy the bundled template into a new project, rebranding
2
+ the ``shaapi`` identifier to the user's project name.
3
+
4
+ Kept intentionally dependency-free (pure stdlib) so the ``shaapi`` CLI stays
5
+ tiny — the heavy stack lives only in the generated project.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ import shutil
11
+ import subprocess
12
+ from pathlib import Path
13
+
14
+ TEMPLATE_DIR = Path(__file__).resolve().parent / "template"
15
+
16
+ # Path components never copied into a generated project.
17
+ _EXCLUDE_NAMES = {
18
+ "__pycache__", ".venv", "venv", ".git", ".pytest_cache", ".ruff_cache",
19
+ ".mypy_cache", "node_modules", ".env", ".DS_Store",
20
+ }
21
+ # Suffixes never copied at all (local dev artifacts).
22
+ _SKIP_SUFFIXES = {".pyc", ".pyo", ".db", ".sqlite3", ".log"}
23
+ # Binary files: copied verbatim, never text-substituted.
24
+ _BINARY_SUFFIXES = {
25
+ ".png", ".jpg", ".jpeg", ".gif", ".ico", ".xdb",
26
+ ".woff", ".woff2", ".ttf", ".pdf", ".zip", ".gz",
27
+ }
28
+
29
+
30
+ def slugify(name: str) -> str:
31
+ """Turn a project name into a safe lowercase identifier slug."""
32
+ slug = re.sub(r"[^0-9a-zA-Z]+", "_", name.strip().lower()).strip("_")
33
+ if not slug:
34
+ raise ValueError("Project name must contain at least one letter or digit.")
35
+ if slug[0].isdigit():
36
+ slug = f"app_{slug}"
37
+ return slug
38
+
39
+
40
+ def _rebrand(text: str, slug: str) -> str:
41
+ """Replace the shaapi identifier with the project slug, preserving case."""
42
+ text = text.replace("SHAAPI", slug.upper())
43
+ text = text.replace("Shaapi", slug.capitalize())
44
+ text = text.replace("shaapi", slug)
45
+ return text
46
+
47
+
48
+ def create_project(
49
+ name: str,
50
+ dest_parent: Path | str,
51
+ *,
52
+ monitoring: bool = False,
53
+ git_init: bool = True,
54
+ ) -> Path:
55
+ """Generate a new shaapi project and return its path.
56
+
57
+ :param name: human project name (e.g. "My API").
58
+ :param dest_parent: directory in which the project folder is created.
59
+ :param monitoring: include the opt-in Prometheus/Grafana stack.
60
+ :param git_init: run ``git init`` in the new project.
61
+ """
62
+ if not TEMPLATE_DIR.is_dir():
63
+ raise RuntimeError(f"Template not found at {TEMPLATE_DIR}")
64
+
65
+ slug = slugify(name)
66
+ dest = Path(dest_parent).resolve() / slug
67
+ if dest.exists():
68
+ raise FileExistsError(f"Directory already exists: {dest}")
69
+
70
+ for src in sorted(TEMPLATE_DIR.rglob("*")):
71
+ rel = src.relative_to(TEMPLATE_DIR)
72
+ if any(part in _EXCLUDE_NAMES for part in rel.parts):
73
+ continue
74
+ if src.is_dir():
75
+ continue
76
+ if src.suffix in _SKIP_SUFFIXES:
77
+ continue
78
+ # Monitoring is opt-in: drop its compose file and the etc/ configs.
79
+ if not monitoring and (
80
+ src.name == "docker-compose.monitoring.yml" or rel.parts[0] == "etc"
81
+ ):
82
+ continue
83
+
84
+ target = dest / Path(_rebrand(str(rel), slug))
85
+ target.parent.mkdir(parents=True, exist_ok=True)
86
+
87
+ if src.suffix in _BINARY_SUFFIXES:
88
+ shutil.copy2(src, target)
89
+ continue
90
+ try:
91
+ content = src.read_text(encoding="utf-8")
92
+ except UnicodeDecodeError:
93
+ shutil.copy2(src, target)
94
+ continue
95
+ # Force LF: the generated project targets Linux/Docker, and CRLF would
96
+ # break shell scripts and .env files inside containers. newline="\n"
97
+ # disables Windows' \n -> \r\n translation.
98
+ target.write_text(_rebrand(content, slug), encoding="utf-8", newline="\n")
99
+
100
+ # Seed a ready-to-run .env from the template.
101
+ env_template = dest / ".env.template"
102
+ env_file = dest / ".env"
103
+ if env_template.exists() and not env_file.exists():
104
+ env_file.write_text(
105
+ env_template.read_text(encoding="utf-8"), encoding="utf-8", newline="\n"
106
+ )
107
+
108
+ if git_init:
109
+ try:
110
+ subprocess.run(["git", "init", "-q"], cwd=dest, check=True)
111
+ except (subprocess.CalledProcessError, FileNotFoundError, OSError):
112
+ pass # git is optional; never fail project creation over it
113
+
114
+ return dest
@@ -0,0 +1,37 @@
1
+ # Version control
2
+ .git
3
+ .gitignore
4
+ .gitlab-ci.yml
5
+
6
+ # Python
7
+ __pycache__/
8
+ *.py[cod]
9
+ *.egg-info/
10
+ .venv/
11
+ venv/
12
+ .pytest_cache/
13
+ .mypy_cache/
14
+ .ruff_cache/
15
+
16
+ # Env & secrets
17
+ .env
18
+ .env.*
19
+ !.env.template
20
+
21
+ # OS / editor
22
+ .DS_Store
23
+ .vscode/
24
+ .idea/
25
+
26
+ # Local data & build artifacts
27
+ *.db
28
+ *.sqlite3
29
+ dist/
30
+ build/
31
+ node_modules/
32
+ *.log
33
+
34
+ # Docs / CI assets not needed in image
35
+ .github/
36
+ docs/
37
+ README.md
@@ -0,0 +1,59 @@
1
+ # shaapi environment configuration
2
+ # Copy to `.env` and adjust. Every value has a sane default in
3
+ # backend/core/conf.py, so you only need to override what differs.
4
+ #
5
+ # When running with docker-compose, the database/redis/minio hosts are
6
+ # overridden to the container service names by the compose file, so the
7
+ # localhost values below are meant for bare-metal local development.
8
+
9
+ # Environment: dev | preprod | prod
10
+ ENVIRONMENT=dev
11
+
12
+ # --- Database (Postgres) ---
13
+ POSTGRES_HOST=localhost
14
+ POSTGRES_PORT=5432
15
+ POSTGRES_USER=postgres
16
+ POSTGRES_PASSWORD=postgres
17
+ POSTGRES_DATABASE=shaapi
18
+
19
+ # Auto-create tables on startup (dev only). Set to false in production and use
20
+ # Alembic migrations instead.
21
+ DB_AUTO_CREATE=true
22
+
23
+ # --- Redis ---
24
+ REDIS_HOST=localhost
25
+ REDIS_PORT=6379
26
+ REDIS_PASSWORD=
27
+ REDIS_DATABASE=0
28
+
29
+ # --- Object storage (MinIO / S3-compatible) ---
30
+ MINIO_ENDPOINT=localhost:9000
31
+ MINIO_PORT=9000
32
+ MINIO_ACCESS_KEY=minioadmin
33
+ MINIO_SECRET_KEY=minioadmin
34
+ MINIO_BUCKET_NAME=shaapi
35
+ MINIO_CLOUD_URL=http://localhost:9000
36
+
37
+ # --- Secrets (CHANGE THESE IN PRODUCTION) ---
38
+ # python -c "import secrets; print(secrets.token_urlsafe(32))"
39
+ TOKEN_SECRET_KEY=dev-insecure-change-me-token-secret-key
40
+ # python -c "import os; print(os.urandom(32).hex())"
41
+ OPERA_LOG_ENCRYPT_SECRET_KEY=dev-insecure-change-me-opera-log-key
42
+
43
+ # --- Optional: SMTP / email (leave blank to disable) ---
44
+ SMTP_HOST=
45
+ SMTP_PORT=587
46
+ SMTP_TLS=True
47
+ SMTP_USER=
48
+ SMTP_PASSWORD=
49
+ EMAILS_FROM_EMAIL=
50
+ EMAILS_FROM_NAME=
51
+
52
+ # --- Optional: Google SSO ---
53
+ GOOGLE_CLIENT_ID=
54
+ GOOGLE_SECRET_KEY=
55
+ GOOGLE_WEBHOOK_OAUTH_REDIRECT_URI=
56
+
57
+ # --- Optional: Observability (Prometheus / OpenTelemetry) ---
58
+ OBSERVABILITY_ENABLED=false
59
+ OTLP_GRPC_ENDPOINT=
@@ -0,0 +1,12 @@
1
+ # Normalize line endings to LF in the repository (Linux/Docker target)
2
+ * text=auto eol=lf
3
+
4
+ # Shell scripts MUST keep LF or they break inside Linux containers
5
+ *.sh text eol=lf
6
+
7
+ # Binary assets (never normalize)
8
+ *.png binary
9
+ *.jpg binary
10
+ *.ico binary
11
+ *.xdb binary
12
+ *.db binary
@@ -0,0 +1,170 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+ .env.elastic
9
+
10
+ # Distribution / packaging
11
+ .Python
12
+ # build/
13
+ develop-eggs/
14
+ dist/
15
+ downloads/
16
+ /node_modules
17
+ eggs/
18
+ .eggs/
19
+ lib/
20
+ lib64/
21
+ parts/
22
+ sdist/
23
+ var/
24
+ wheels/
25
+ share/python-wheels/
26
+ *.egg-info/
27
+ .installed.cfg
28
+ *.egg
29
+ MANIFEST
30
+
31
+ # private_key.pem
32
+ # public_key.pem
33
+
34
+ # PyInstaller
35
+ # Usually these files are written by a python script from a template
36
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
37
+ *.manifest
38
+ *.spec
39
+
40
+ # Installer logs
41
+ pip-log.txt
42
+ pip-delete-this-directory.txt
43
+
44
+ # Unit test / coverage reports
45
+ htmlcov/
46
+ .tox/
47
+ .nox/
48
+ .coverage
49
+ .coverage.*
50
+ .cache
51
+ nosetests.xml
52
+ coverage.xml
53
+ *.cover
54
+ *.py,cover
55
+ .hypothesis/
56
+ .pytest_cache/
57
+ cover/
58
+
59
+ # Translations
60
+ *.mo
61
+ *.pot
62
+
63
+ # Django stuff:
64
+ *.log
65
+ local_settings.py
66
+ db.sqlite3
67
+ db.sqlite3-journal
68
+
69
+ # Flask stuff:
70
+ instance/
71
+ .webassets-cache
72
+
73
+ # Scrapy stuff:
74
+ .scrapy
75
+
76
+ # Sphinx documentation
77
+ docs/_build/
78
+
79
+ # PyBuilder
80
+ .pybuilder/
81
+ target/
82
+
83
+ # Jupyter Notebook
84
+ .ipynb_checkpoints
85
+
86
+ # IPython
87
+ profile_default/
88
+ ipython_config.py
89
+
90
+ # pyenv
91
+ # For a library or package, you might want to ignore these files since the code is
92
+ # intended to run in multiple environments; otherwise, check them in:
93
+ # .python-version
94
+
95
+ # pipenv
96
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
97
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
98
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
99
+ # install all needed dependencies.
100
+ #Pipfile.lock
101
+
102
+ # poetry
103
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
104
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
105
+ # commonly ignored for libraries.
106
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
107
+ #poetry.lock
108
+
109
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
110
+ __pypackages__/
111
+
112
+ # Celery stuff
113
+ celerybeat-schedule
114
+ celerybeat.pid
115
+
116
+ # SageMath parsed files
117
+ *.sage.py
118
+
119
+ # Environments
120
+ .env
121
+ .env.elastic
122
+ .venv
123
+ env/
124
+ venv/
125
+ ENV/
126
+ env.bak/
127
+ venv.bak/
128
+ fastapi-boilerplate-venv/
129
+
130
+ # Spyder project settings
131
+ .spyderproject
132
+ .spyproject
133
+
134
+ # Rope project settings
135
+ .ropeproject
136
+
137
+ # mkdocs documentation
138
+ /site
139
+
140
+ # mypy
141
+ .mypy_cache/
142
+ .dmypy.json
143
+ dmypy.json
144
+
145
+ # Pyre type checker
146
+ .pyre/
147
+
148
+ # pytype static type analyzer
149
+ .pytype/
150
+
151
+ # Cython debug symbols
152
+ cython_debug/
153
+ /boilerplate-venv
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
161
+ .history/
162
+
163
+
164
+ changelog.config.js
165
+
166
+ # macOS
167
+ .DS_Store
168
+
169
+ # uv (commit uv.lock for reproducibility)
170
+ .venv/
@@ -0,0 +1,89 @@
1
+ image:
2
+ name: docker/compose:1.29.1
3
+ entrypoint: [""]
4
+
5
+ services:
6
+ - docker:dind
7
+
8
+ stages:
9
+ - build
10
+ - release
11
+ - deploy
12
+
13
+ variables:
14
+ DOCKER_HOST: tcp://docker:2375
15
+ DOCKER_DRIVER: overlay2
16
+ DOCKER_TLS_CERTDIR: ""
17
+
18
+ # the way to re-use the same steps for every stage in the workflow in the configuration file
19
+ before_script:
20
+ # export the environment variable for an address of where our Docker image gets stored
21
+ - export IMAGE=$CI_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME
22
+ # Installs the open-ssh client for later login to our vps
23
+ # and Bash to execute the Bash script for setting up the environment variable.
24
+ - apk add --no-cache openssh-client bash
25
+ - echo "$CI_JOB_TOKEN" | docker login -u "$CI_REGISTRY_USER" --password-stdin $CI_REGISTRY
26
+ # - docker login -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN $CI_REGISTRY
27
+ - chmod +x ./devops/scripts/setup_env.sh
28
+ - bash ./devops/scripts/setup_env.sh
29
+
30
+ build:
31
+ stage: build
32
+ script:
33
+ - export API_IMAGE=$IMAGE:api
34
+ # Pull the image if it exists in the registry.
35
+ - docker pull $IMAGE:api || true
36
+ # Build the image based on the configuration we have in the docker-compose.ci.yml file
37
+ - docker-compose -f ./devops/docker-compose/docker-compose-ci.yml build
38
+ # After the image has been built, it pushes the latest build image back to the GitLab Docker image registry
39
+ - docker push $IMAGE:api
40
+ only:
41
+ - prod
42
+ # when: manual
43
+
44
+ release:
45
+ stage: release
46
+ script:
47
+ - apk add --update nodejs git npm
48
+ - git config --global user.email "admin@kaanari.com"
49
+ - git config --global user.name "nicolas"
50
+ - git tag -d v0.1.1 || true
51
+ - git push --delete origin v0.1.1 || true
52
+ - mkdir -p ~/.ssh
53
+ - echo "$PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa
54
+ - cat ~/.ssh/id_rsa
55
+ - chmod 700 ~/.ssh/id_rsa
56
+ - eval "$(ssh-agent -s)"
57
+ - ssh-add ~/.ssh/id_rsa
58
+ - ssh-keyscan -H gitlab.organisation.com >> ~/.ssh/known_hosts
59
+ - git remote set-url origin git@gitlab.organisation.com:boilerplate/boilerplate.git
60
+ - npm install
61
+ - npm ci
62
+ - npm run release
63
+ - git remote show origin
64
+ - git push --follow-tags origin HEAD:main
65
+ only:
66
+ - deploy
67
+
68
+ deploy:
69
+ stage: deploy
70
+ script:
71
+ - export API_IMAGE=$IMAGE:api
72
+ # Extract a private key that is going to be used for SSH to the droplet and add it to the GitLab CI/CD process.
73
+ - mkdir -p ~/.ssh
74
+ - echo "$PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa
75
+ # - cat ~/.ssh/id_rsa
76
+ - chmod 700 ~/.ssh/id_rsa
77
+ # Copy all of the required artifacts for the deployment to the droplet by SSH-ing to it.
78
+ - eval "$(ssh-agent -s)"
79
+ - ssh-add ~/.ssh/id_rsa
80
+ - ssh-keyscan -H "$VPS_IP_ADDRESS" >> ~/.ssh/known_hosts
81
+ - chmod +x ./devops/scripts/deploy.sh
82
+ # - chmod +x ./clean.sh
83
+ # - bash ./clean.sh
84
+ - scp -o StrictHostKeyChecking=no -r ./.env ./devops/docker-compose/docker-compose.yml $VPS_USER@$VPS_IP_ADDRESS:/app
85
+ # # Run the deployment script
86
+ - bash ./devops/scripts/deploy.sh
87
+ only:
88
+ - prod
89
+ # when: manual
@@ -0,0 +1,59 @@
1
+ # syntax=docker/dockerfile:1
2
+ # ============================================================================
3
+ # Stage 1 — builder: resolve & install dependencies into an isolated venv
4
+ # ============================================================================
5
+ FROM python:3.11-slim AS builder
6
+
7
+ # uv binary (fast, reproducible installs)
8
+ COPY --from=ghcr.io/astral-sh/uv:0.11 /uv /uvx /bin/
9
+
10
+ WORKDIR /app
11
+
12
+ ENV UV_COMPILE_BYTECODE=1 \
13
+ UV_LINK_MODE=copy \
14
+ UV_PYTHON_DOWNLOADS=never \
15
+ # Keep the venv OUTSIDE /app so a dev bind-mount of the source (.:/app)
16
+ # never shadows the installed dependencies.
17
+ UV_PROJECT_ENVIRONMENT=/opt/venv
18
+
19
+ # System build dependencies (asyncpg / cryptography / libpq)
20
+ RUN apt-get update \
21
+ && apt-get install -y --no-install-recommends build-essential libpq-dev \
22
+ && rm -rf /var/lib/apt/lists/*
23
+
24
+ # Optional extras (e.g. "--extra monitoring"); empty for the lean default.
25
+ ARG EXTRAS=""
26
+
27
+ # Install dependencies first (cached layer; only re-runs when deps change)
28
+ COPY pyproject.toml uv.lock ./
29
+ RUN uv sync --frozen --no-dev --no-install-project ${EXTRAS}
30
+
31
+ # ============================================================================
32
+ # Stage 2 — runtime: slim image with only what's needed to run
33
+ # ============================================================================
34
+ FROM python:3.11-slim
35
+
36
+ WORKDIR /app
37
+
38
+ # Runtime system deps (libpq for Postgres, curl for healthchecks)
39
+ RUN apt-get update \
40
+ && apt-get install -y --no-install-recommends libpq5 curl \
41
+ && rm -rf /var/lib/apt/lists/*
42
+
43
+ # Bring in the pre-built virtualenv (lives outside /app so dev bind-mounts work)
44
+ COPY --from=builder /opt/venv /opt/venv
45
+
46
+ ENV PATH="/opt/venv/bin:$PATH" \
47
+ PYTHONPATH=/app \
48
+ PYTHONUNBUFFERED=1 \
49
+ PYTHONDONTWRITEBYTECODE=1 \
50
+ LANG=C.UTF-8
51
+
52
+ # Application source
53
+ COPY . .
54
+
55
+ RUN chmod +x ./backend/entrypoint-api.sh
56
+
57
+ EXPOSE 8000
58
+
59
+ ENTRYPOINT ["bash", "./backend/entrypoint-api.sh"]
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Kaanari
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.