swiftapi-kernel 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.
Potentially problematic release.
This version of swiftapi-kernel might be problematic. Click here for more details.
- swiftapi/__init__.py +22 -0
- swiftapi/app/__init__.py +0 -0
- swiftapi/app/factory.py +200 -0
- swiftapi/app/lifespan.py +167 -0
- swiftapi/app/routers.py +58 -0
- swiftapi/cli/__init__.py +0 -0
- swiftapi/cli/admin.py +198 -0
- swiftapi/cli/appref.py +51 -0
- swiftapi/cli/audit.py +45 -0
- swiftapi/cli/db.py +185 -0
- swiftapi/cli/endpoint.py +169 -0
- swiftapi/cli/logs.py +100 -0
- swiftapi/cli/main.py +238 -0
- swiftapi/cli/new.py +113 -0
- swiftapi/cli/openapi.py +69 -0
- swiftapi/cli/resource.py +657 -0
- swiftapi/cli/scaffold.py +168 -0
- swiftapi/config/__init__.py +0 -0
- swiftapi/config/constants.py +51 -0
- swiftapi/config/environments.py +38 -0
- swiftapi/config/settings.py +764 -0
- swiftapi/core/__init__.py +0 -0
- swiftapi/core/admin/__init__.py +0 -0
- swiftapi/core/admin/accounts.py +385 -0
- swiftapi/core/admin/audit.py +203 -0
- swiftapi/core/admin/maintenance.py +53 -0
- swiftapi/core/admin/registry.py +53 -0
- swiftapi/core/admin/security.py +94 -0
- swiftapi/core/admin/session.py +154 -0
- swiftapi/core/admin/views.py +2428 -0
- swiftapi/core/cache/__init__.py +0 -0
- swiftapi/core/cache/base.py +29 -0
- swiftapi/core/cache/decorators.py +51 -0
- swiftapi/core/cache/factory.py +30 -0
- swiftapi/core/cache/keys.py +24 -0
- swiftapi/core/cache/memory.py +60 -0
- swiftapi/core/cache/null.py +28 -0
- swiftapi/core/cache/redis.py +50 -0
- swiftapi/core/container.py +209 -0
- swiftapi/core/db/__init__.py +0 -0
- swiftapi/core/db/base_model.py +122 -0
- swiftapi/core/db/crud.py +242 -0
- swiftapi/core/db/dialects/__init__.py +8 -0
- swiftapi/core/db/dialects/base.py +106 -0
- swiftapi/core/db/dialects/mysql.py +47 -0
- swiftapi/core/db/dialects/pg.py +51 -0
- swiftapi/core/db/dialects/registry.py +30 -0
- swiftapi/core/db/dialects/sqlite.py +47 -0
- swiftapi/core/db/engine.py +209 -0
- swiftapi/core/db/health.py +84 -0
- swiftapi/core/db/migrate/__init__.py +1 -0
- swiftapi/core/db/migrate/ddl.py +162 -0
- swiftapi/core/db/migrate/render.py +84 -0
- swiftapi/core/db/migrate/runner.py +159 -0
- swiftapi/core/db/migrate/schema.py +248 -0
- swiftapi/core/db/mixins.py +53 -0
- swiftapi/core/db/session.py +54 -0
- swiftapi/core/db/snapshot.py +33 -0
- swiftapi/core/db/tenant_model.py +43 -0
- swiftapi/core/db/tenant_router.py +114 -0
- swiftapi/core/db/types.py +109 -0
- swiftapi/core/db/unit_of_work.py +65 -0
- swiftapi/core/docs/__init__.py +0 -0
- swiftapi/core/docs/router.py +26 -0
- swiftapi/core/docs/tsgen.py +93 -0
- swiftapi/core/docs/ui.py +132 -0
- swiftapi/core/errors/__init__.py +0 -0
- swiftapi/core/errors/base.py +168 -0
- swiftapi/core/errors/codes.py +117 -0
- swiftapi/core/errors/handlers.py +155 -0
- swiftapi/core/errors/problem.py +58 -0
- swiftapi/core/errors/validation.py +11 -0
- swiftapi/core/framework_models.py +22 -0
- swiftapi/core/http/__init__.py +47 -0
- swiftapi/core/http/app.py +247 -0
- swiftapi/core/http/cors.py +100 -0
- swiftapi/core/http/idempotency.py +148 -0
- swiftapi/core/http/middleware/__init__.py +82 -0
- swiftapi/core/http/middleware/access_log.py +57 -0
- swiftapi/core/http/middleware/auth.py +105 -0
- swiftapi/core/http/middleware/body_limit.py +76 -0
- swiftapi/core/http/middleware/rate_limit.py +103 -0
- swiftapi/core/http/middleware/request_body.py +122 -0
- swiftapi/core/http/middleware/request_id.py +46 -0
- swiftapi/core/http/middleware/security_headers.py +46 -0
- swiftapi/core/http/middleware/tenant.py +93 -0
- swiftapi/core/http/middleware/timing.py +57 -0
- swiftapi/core/http/multipart.py +116 -0
- swiftapi/core/http/multipart_stream.py +216 -0
- swiftapi/core/http/openapi.py +148 -0
- swiftapi/core/http/pagination.py +55 -0
- swiftapi/core/http/params.py +302 -0
- swiftapi/core/http/request.py +145 -0
- swiftapi/core/http/responses.py +127 -0
- swiftapi/core/http/routing.py +200 -0
- swiftapi/core/http/types.py +86 -0
- swiftapi/core/http/uploads.py +222 -0
- swiftapi/core/messaging/__init__.py +0 -0
- swiftapi/core/messaging/base.py +33 -0
- swiftapi/core/messaging/consumer.py +57 -0
- swiftapi/core/messaging/factory.py +30 -0
- swiftapi/core/messaging/idempotency.py +61 -0
- swiftapi/core/messaging/inprocess.py +30 -0
- swiftapi/core/messaging/outbox.py +106 -0
- swiftapi/core/messaging/rabbitmq.py +186 -0
- swiftapi/core/messaging/relay.py +151 -0
- swiftapi/core/messaging/streams.py +141 -0
- swiftapi/core/observability/__init__.py +0 -0
- swiftapi/core/observability/archive.py +136 -0
- swiftapi/core/observability/context.py +102 -0
- swiftapi/core/observability/logging.py +192 -0
- swiftapi/core/observability/masking.py +74 -0
- swiftapi/core/observability/metrics.py +101 -0
- swiftapi/core/observability/volume.py +67 -0
- swiftapi/core/resilience/__init__.py +0 -0
- swiftapi/core/resilience/bulkhead.py +50 -0
- swiftapi/core/resilience/circuit_breaker.py +97 -0
- swiftapi/core/resilience/client.py +179 -0
- swiftapi/core/resilience/retry.py +59 -0
- swiftapi/core/security/__init__.py +0 -0
- swiftapi/core/security/jwt.py +78 -0
- swiftapi/core/security/principal.py +78 -0
- swiftapi/core/tenant/__init__.py +1 -0
- swiftapi/core/tenant/catalog.py +89 -0
- swiftapi/core/tenant/context.py +75 -0
- swiftapi/core/tenant/isolation.py +48 -0
- swiftapi/core/tenant/resolver.py +48 -0
- swiftapi/core/validation/__init__.py +0 -0
- swiftapi/core/validation/base.py +32 -0
- swiftapi/db.py +50 -0
- swiftapi/modules/__init__.py +0 -0
- swiftapi/modules/users/__init__.py +11 -0
- swiftapi/modules/users/api/__init__.py +0 -0
- swiftapi/modules/users/api/users.py +110 -0
- swiftapi/modules/users/crud/__init__.py +0 -0
- swiftapi/modules/users/crud/user.py +23 -0
- swiftapi/modules/users/errors.py +24 -0
- swiftapi/modules/users/mappers.py +19 -0
- swiftapi/modules/users/model/__init__.py +0 -0
- swiftapi/modules/users/model/user.py +37 -0
- swiftapi/modules/users/policies.py +19 -0
- swiftapi/modules/users/schema/__init__.py +0 -0
- swiftapi/modules/users/schema/user.py +40 -0
- swiftapi/modules/users/service/__init__.py +0 -0
- swiftapi/modules/users/service/user.py +107 -0
- swiftapi/py.typed +0 -0
- swiftapi/templates/__init__.py +0 -0
- swiftapi/templates/app_skeleton/README.md +17 -0
- swiftapi/templates/app_skeleton/__init__.py +1 -0
- swiftapi/templates/app_skeleton/api/__init__.py +23 -0
- swiftapi/templates/app_skeleton/api/health.py +12 -0
- swiftapi/templates/app_skeleton/crud/__init__.py +1 -0
- swiftapi/templates/app_skeleton/model/__init__.py +1 -0
- swiftapi/templates/app_skeleton/router.py +16 -0
- swiftapi/templates/app_skeleton/schema/__init__.py +1 -0
- swiftapi/templates/app_skeleton/service/__init__.py +1 -0
- swiftapi/templates/project/__init__.py +0 -0
- swiftapi/templates/project/api.py +135 -0
- swiftapi/templates/project/app.py +57 -0
- swiftapi/templates/project/endpoints/__init__.py +25 -0
- swiftapi/templates/project/events.py +43 -0
- swiftapi/templates/project/models.py +79 -0
- swiftapi/templates/project/resources/__init__.py +35 -0
- swiftapi/templates/project/schemas.py +45 -0
- swiftapi/templates/project/service.py +125 -0
- swiftapi/templates/project/settings.py +17 -0
- swiftapi/templates/project_skeleton/.env.example +5 -0
- swiftapi/templates/project_skeleton/.gitignore +6 -0
- swiftapi/templates/project_skeleton/README.md +25 -0
- swiftapi/templates/project_skeleton/__init__.py +1 -0
- swiftapi/templates/project_skeleton/app.py +26 -0
- swiftapi/templates/project_skeleton/apps/__init__.py +1 -0
- swiftapi/templates/project_skeleton/common/__init__.py +4 -0
- swiftapi/templates/project_skeleton/conf/__init__.py +1 -0
- swiftapi/templates/project_skeleton/conf/settings.py +73 -0
- swiftapi/templates/project_skeleton/logs/.gitkeep +0 -0
- swiftapi/templates/project_skeleton/models.py +12 -0
- swiftapi/templates/project_skeleton/nginx/nginx.conf +20 -0
- swiftapi/templates/project_skeleton/router.py +46 -0
- swiftapi/templates/project_skeleton/script/start.sh +13 -0
- swiftapi/templates/project_skeleton/start.py +35 -0
- swiftapi/version.py +8 -0
- swiftapi_kernel-0.1.0.dist-info/METADATA +962 -0
- swiftapi_kernel-0.1.0.dist-info/RECORD +187 -0
- swiftapi_kernel-0.1.0.dist-info/WHEEL +4 -0
- swiftapi_kernel-0.1.0.dist-info/entry_points.txt +3 -0
- swiftapi_kernel-0.1.0.dist-info/licenses/LICENSE +201 -0
swiftapi/cli/main.py
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
"""`swiftapi` 命令行:配置查看、启动自检、本地启动。
|
|
2
|
+
|
|
3
|
+
CLI 只做"人要看的事",不承担任何业务逻辑,也不连接数据库。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import socket
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
|
|
14
|
+
import typer
|
|
15
|
+
from rich.console import Console
|
|
16
|
+
from rich.table import Table
|
|
17
|
+
|
|
18
|
+
from swiftapi.cli.admin import admin_app
|
|
19
|
+
from swiftapi.cli.appref import discover_app_reference, import_factory
|
|
20
|
+
from swiftapi.cli.audit import audit_app
|
|
21
|
+
from swiftapi.cli.db import db_app
|
|
22
|
+
from swiftapi.cli.logs import logs_app
|
|
23
|
+
from swiftapi.cli.new import new_app
|
|
24
|
+
from swiftapi.cli.openapi import openapi_app
|
|
25
|
+
from swiftapi.cli.scaffold import scaffold_app
|
|
26
|
+
from swiftapi.config.settings import (
|
|
27
|
+
Settings,
|
|
28
|
+
SettingsError,
|
|
29
|
+
discover_settings_module,
|
|
30
|
+
load_settings,
|
|
31
|
+
)
|
|
32
|
+
from swiftapi.version import __version__
|
|
33
|
+
|
|
34
|
+
app = typer.Typer(
|
|
35
|
+
name="swiftapi",
|
|
36
|
+
help="SwiftAPI 工程内核 CLI",
|
|
37
|
+
no_args_is_help=True,
|
|
38
|
+
add_completion=False,
|
|
39
|
+
)
|
|
40
|
+
config_app = typer.Typer(help="配置:查看生效值(已脱敏)", no_args_is_help=True)
|
|
41
|
+
app.add_typer(config_app, name="config")
|
|
42
|
+
app.add_typer(db_app, name="db")
|
|
43
|
+
app.add_typer(openapi_app, name="openapi")
|
|
44
|
+
app.add_typer(new_app, name="new")
|
|
45
|
+
app.add_typer(scaffold_app)
|
|
46
|
+
app.add_typer(logs_app, name="logs")
|
|
47
|
+
app.add_typer(audit_app, name="audit")
|
|
48
|
+
app.add_typer(admin_app, name="admin")
|
|
49
|
+
|
|
50
|
+
console = Console()
|
|
51
|
+
|
|
52
|
+
# 与 Django 的 manage.py 一致:CLI 以"当前目录"为项目根
|
|
53
|
+
if os.getcwd() not in sys.path:
|
|
54
|
+
sys.path.insert(0, os.getcwd())
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _load_or_exit(settings_module: str | None = None) -> Settings:
|
|
58
|
+
try:
|
|
59
|
+
return load_settings(settings_module)
|
|
60
|
+
except SettingsError as exc:
|
|
61
|
+
console.print(f"[red]{exc}[/red]")
|
|
62
|
+
raise typer.Exit(code=1) from exc
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@app.command()
|
|
66
|
+
def version() -> None:
|
|
67
|
+
"""打印版本号。"""
|
|
68
|
+
console.print(f"swiftapi {__version__}")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@config_app.command("show")
|
|
72
|
+
def config_show(
|
|
73
|
+
settings: str | None = typer.Option(None, "--settings", "-s", help="settings 模块路径"),
|
|
74
|
+
as_json: bool = typer.Option(False, "--json", help="输出机器可读 JSON(含来源)"),
|
|
75
|
+
) -> None:
|
|
76
|
+
"""打印生效配置摘要(密钥只显示指纹)+ 配置来源。"""
|
|
77
|
+
from swiftapi.config.settings import active_settings_source
|
|
78
|
+
|
|
79
|
+
settings_obj = _load_or_exit(settings)
|
|
80
|
+
source = active_settings_source()
|
|
81
|
+
summary = settings_obj.redacted_summary()
|
|
82
|
+
|
|
83
|
+
if as_json:
|
|
84
|
+
console.print_json(json.dumps({"source": source, "settings": summary}, ensure_ascii=False, default=str))
|
|
85
|
+
return
|
|
86
|
+
|
|
87
|
+
table = Table(title="配置来源")
|
|
88
|
+
table.add_column("项")
|
|
89
|
+
table.add_column("值")
|
|
90
|
+
table.add_row("settings 模块", str(source.get("module") or "内核默认值"))
|
|
91
|
+
mode = "自动发现" if source.get("discovered") else ("环境变量" if source.get("from_env") else "显式/默认")
|
|
92
|
+
table.add_row("发现方式", mode)
|
|
93
|
+
table.add_row("工作目录", str(source.get("cwd") or "-"))
|
|
94
|
+
table.add_row("数据库", str(source.get("database") or "-"))
|
|
95
|
+
console.print(table)
|
|
96
|
+
console.print_json(json.dumps(summary, ensure_ascii=False, default=str))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@app.command()
|
|
100
|
+
def check(
|
|
101
|
+
settings: str | None = typer.Option(None, "--settings", "-s", help="settings 模块路径"),
|
|
102
|
+
) -> None:
|
|
103
|
+
"""启动自检:配置校验 + 依赖图校验(不连接任何外部服务)。"""
|
|
104
|
+
from swiftapi.app.factory import build_container
|
|
105
|
+
from swiftapi.core.db.engine import create_database
|
|
106
|
+
|
|
107
|
+
settings_obj = _load_or_exit(settings)
|
|
108
|
+
database = create_database(settings_obj)
|
|
109
|
+
container = build_container(settings_obj, database)
|
|
110
|
+
|
|
111
|
+
table = Table(title="启动自检")
|
|
112
|
+
table.add_column("检查项")
|
|
113
|
+
table.add_column("结果")
|
|
114
|
+
|
|
115
|
+
table.add_row("配置加载", "[green]OK[/green]")
|
|
116
|
+
failed = False
|
|
117
|
+
try:
|
|
118
|
+
container.seal()
|
|
119
|
+
table.add_row("依赖图", f"[green]OK[/green]({len(container.keys)} 个 provider)")
|
|
120
|
+
except Exception as exc:
|
|
121
|
+
table.add_row("依赖图", f"[red]FAIL[/red] {exc}")
|
|
122
|
+
failed = True
|
|
123
|
+
|
|
124
|
+
table.add_row("数据库方言", settings_obj.database.dialect)
|
|
125
|
+
table.add_row("多租户", "开启" if settings_obj.tenant.enabled else "关闭")
|
|
126
|
+
try:
|
|
127
|
+
_check_project_app(settings_obj, table)
|
|
128
|
+
except Exception as exc:
|
|
129
|
+
table.add_row("项目应用", f"[red]FAIL[/red] {exc}")
|
|
130
|
+
failed = True
|
|
131
|
+
|
|
132
|
+
console.print(table)
|
|
133
|
+
import asyncio
|
|
134
|
+
|
|
135
|
+
asyncio.run(database.aclose())
|
|
136
|
+
if failed:
|
|
137
|
+
raise typer.Exit(code=1)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _check_project_app(settings_obj: object, table: Table) -> None:
|
|
141
|
+
"""构建项目应用并生成一次 OpenAPI:路由 import 错误在 check 阶段暴露。"""
|
|
142
|
+
from swiftapi.cli.appref import (
|
|
143
|
+
KERNEL_APP,
|
|
144
|
+
call_factory,
|
|
145
|
+
discover_app_reference,
|
|
146
|
+
import_factory,
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
reference = discover_app_reference()
|
|
150
|
+
if reference == KERNEL_APP:
|
|
151
|
+
table.add_row("项目应用", "[dim]未发现(使用内核默认应用)[/dim]")
|
|
152
|
+
return
|
|
153
|
+
app = call_factory(import_factory(reference), settings_obj)
|
|
154
|
+
paths = app.openapi()["paths"]
|
|
155
|
+
table.add_row("项目应用", f"[green]OK[/green]({reference},{len(paths)} 个路径)")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _port_owner(port: int) -> str:
|
|
159
|
+
"""尽量查出端口占用者(macOS/Linux 的 lsof;查不到就空串)。"""
|
|
160
|
+
try:
|
|
161
|
+
output = subprocess.run(
|
|
162
|
+
["lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-F", "pcn"],
|
|
163
|
+
capture_output=True,
|
|
164
|
+
text=True,
|
|
165
|
+
timeout=2,
|
|
166
|
+
).stdout
|
|
167
|
+
except (OSError, subprocess.SubprocessError):
|
|
168
|
+
return ""
|
|
169
|
+
pid = command = ""
|
|
170
|
+
for line in output.splitlines():
|
|
171
|
+
if line.startswith("p"):
|
|
172
|
+
pid = line[1:]
|
|
173
|
+
elif line.startswith("c"):
|
|
174
|
+
command = line[1:]
|
|
175
|
+
if pid and command:
|
|
176
|
+
return f"PID {pid}({command})"
|
|
177
|
+
return ""
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _assert_port_free(host: str, port: int) -> None:
|
|
181
|
+
"""启动前检查端口:uvicorn 的报错发生在 lifespan 之后,容易误读成"启动又崩了"。"""
|
|
182
|
+
# 用 connect 探测而不是 bind:SO_REUSEADDR 会让 bind 在 macOS 上"假成功"
|
|
183
|
+
target = "127.0.0.1" if host in {"0.0.0.0", "::", ""} else host # nosec B104 - 仅比较,不绑定
|
|
184
|
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
|
|
185
|
+
probe.settimeout(0.3)
|
|
186
|
+
occupied = probe.connect_ex((target, port)) == 0
|
|
187
|
+
if occupied:
|
|
188
|
+
owner = _port_owner(port)
|
|
189
|
+
hint = f",占用者:{owner}" if owner else ""
|
|
190
|
+
console.print(
|
|
191
|
+
f"[red]端口 {port} 已被占用[/red]{hint}\n"
|
|
192
|
+
f" → 换端口:swiftapi run --port {port + 1}\n"
|
|
193
|
+
f" → 或停止占用进程:lsof -tiTCP:{port} -sTCP:LISTEN | xargs kill"
|
|
194
|
+
)
|
|
195
|
+
raise typer.Exit(code=1)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
@app.command()
|
|
199
|
+
def run(
|
|
200
|
+
host: str = typer.Option("127.0.0.1", help="监听地址(公网部署显式传 0.0.0.0)"),
|
|
201
|
+
port: int = typer.Option(8000, help="监听端口"),
|
|
202
|
+
reload: bool = typer.Option(False, help="开发模式自动重载"),
|
|
203
|
+
app_ref: str | None = typer.Option(
|
|
204
|
+
None, "--app", help="应用工厂,如 mall.app:create_app(默认自动发现项目)"
|
|
205
|
+
),
|
|
206
|
+
) -> None:
|
|
207
|
+
"""本地启动服务(生产请用 uvicorn/gunicorn 直接托管)。"""
|
|
208
|
+
import uvicorn
|
|
209
|
+
|
|
210
|
+
_assert_port_free(host, port)
|
|
211
|
+
reference = discover_app_reference(app_ref)
|
|
212
|
+
found = discover_settings_module()
|
|
213
|
+
# reload 会另起子进程:用 app_dir 保证子进程也能导入项目包
|
|
214
|
+
app_dir = str(found[1].parent) if found is not None else None
|
|
215
|
+
|
|
216
|
+
if reload:
|
|
217
|
+
uvicorn.run(
|
|
218
|
+
reference,
|
|
219
|
+
factory=True,
|
|
220
|
+
host=host,
|
|
221
|
+
port=port,
|
|
222
|
+
reload=True,
|
|
223
|
+
app_dir=app_dir,
|
|
224
|
+
)
|
|
225
|
+
else:
|
|
226
|
+
uvicorn.run(import_factory(reference)(), host=host, port=port)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def main() -> None: # pragma: no cover - 进程入口
|
|
230
|
+
try:
|
|
231
|
+
app()
|
|
232
|
+
except SettingsError as exc:
|
|
233
|
+
print(str(exc), file=sys.stderr)
|
|
234
|
+
raise SystemExit(1) from exc
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
if __name__ == "__main__": # pragma: no cover
|
|
238
|
+
main()
|
swiftapi/cli/new.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"""`swiftapi new project`:从内置模板生成一个可运行项目(DX G5)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from importlib.resources import files
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
import typer
|
|
12
|
+
from rich.console import Console
|
|
13
|
+
|
|
14
|
+
from swiftapi.cli.endpoint import create_endpoint
|
|
15
|
+
from swiftapi.cli.resource import create_resource
|
|
16
|
+
|
|
17
|
+
new_app = typer.Typer(help="脚手架:生成项目骨架", no_args_is_help=True)
|
|
18
|
+
new_app.command("endpoint")(create_endpoint)
|
|
19
|
+
new_app.command("resource")(create_resource)
|
|
20
|
+
console = Console()
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@new_app.command("project")
|
|
24
|
+
def project(
|
|
25
|
+
name: str = typer.Argument(..., help="项目包名(小写下划线)"),
|
|
26
|
+
path: Path = typer.Option(Path("."), "--path", "-p", help="生成到哪个目录"),
|
|
27
|
+
force: bool = typer.Option(False, "--force", help="目标已存在时覆盖"),
|
|
28
|
+
) -> None:
|
|
29
|
+
"""复制内置模板并替换包名(模板来自 examples/helpdesk 的最佳实践)。"""
|
|
30
|
+
if not name.isidentifier():
|
|
31
|
+
console.print(f"[red]非法包名: {name!r}(需符合 Python 标识符)[/red]")
|
|
32
|
+
raise typer.Exit(code=1)
|
|
33
|
+
|
|
34
|
+
destination = Path(path) / name
|
|
35
|
+
if destination.exists() and not force:
|
|
36
|
+
console.print(f"[red]目录已存在: {destination}(加 --force 覆盖)[/red]")
|
|
37
|
+
raise typer.Exit(code=1)
|
|
38
|
+
|
|
39
|
+
# 模板在安装后始终是磁盘上的真实目录(wheel 解包到 site-packages)
|
|
40
|
+
template_root = Path(str(files("swiftapi.templates").joinpath("project")))
|
|
41
|
+
destination.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
written = 0
|
|
43
|
+
for entry in sorted(template_root.rglob("*.py")):
|
|
44
|
+
relative = entry.relative_to(template_root)
|
|
45
|
+
content = (
|
|
46
|
+
entry.read_text(encoding="utf-8")
|
|
47
|
+
.replace("__PROJECT__", name)
|
|
48
|
+
.replace('__module_schema__ = "helpdesk"', f'__module_schema__ = "{name}"')
|
|
49
|
+
.replace("helpdesk:", f"{name}:")
|
|
50
|
+
.replace('"title": "Helpdesk API"', f'"title": "{name} API"')
|
|
51
|
+
)
|
|
52
|
+
target_file = destination / relative
|
|
53
|
+
target_file.parent.mkdir(parents=True, exist_ok=True)
|
|
54
|
+
target_file.write_text(content, encoding="utf-8")
|
|
55
|
+
written += 1
|
|
56
|
+
|
|
57
|
+
readme = destination / "README.md"
|
|
58
|
+
readme.write_text(
|
|
59
|
+
f"""# {name}
|
|
60
|
+
|
|
61
|
+
由 `swiftapi new project` 生成。
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
cd {name}
|
|
65
|
+
|
|
66
|
+
# 建表(在项目根目录执行即可,CLI 会自动发现 {name}/settings.py)
|
|
67
|
+
swiftapi db revision --models {name}.models -m "init" --dir migrations
|
|
68
|
+
swiftapi db upgrade --dir migrations
|
|
69
|
+
|
|
70
|
+
# 启动(自动发现 {name}.app:create_app)
|
|
71
|
+
swiftapi run --port 8000
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## 本地签发开发令牌(HS256)
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
python -c "
|
|
78
|
+
import jwt, uuid, datetime
|
|
79
|
+
print(jwt.encode({{'sub': str(uuid.uuid4()), 'roles': ['agent'], 'tid': 'acme',
|
|
80
|
+
'iss': 'swiftapi', 'aud': 'swiftapi',
|
|
81
|
+
'exp': datetime.datetime.now(datetime.UTC) + datetime.timedelta(minutes=30)}},
|
|
82
|
+
'{name}-dev-secret-please-rotate-32', algorithm='HS256'))"
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
TOKEN=<上面的输出>
|
|
87
|
+
curl -H "Authorization: Bearer $TOKEN" localhost:8000/admin
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
- 文档:<http://127.0.0.1:8000/docs>
|
|
91
|
+
- 后台:<http://127.0.0.1:8000/admin>(需 JWT,角色 `admin`)
|
|
92
|
+
""",
|
|
93
|
+
encoding="utf-8",
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
# 语法自检:生成物必须能编译
|
|
97
|
+
check = subprocess.run(
|
|
98
|
+
[sys.executable, "-m", "compileall", "-q", str(destination)],
|
|
99
|
+
capture_output=True,
|
|
100
|
+
text=True,
|
|
101
|
+
)
|
|
102
|
+
if check.returncode != 0:
|
|
103
|
+
console.print(f"[red]生成物编译失败:{check.stderr}[/red]")
|
|
104
|
+
raise typer.Exit(code=1)
|
|
105
|
+
for cache in destination.rglob("__pycache__"):
|
|
106
|
+
shutil.rmtree(cache, ignore_errors=True)
|
|
107
|
+
|
|
108
|
+
console.print(f"[green]已生成[/green] {destination}({written} 个 Python 文件)")
|
|
109
|
+
console.print(
|
|
110
|
+
f"下一步:cd {destination} && swiftapi db revision --models {name}.models "
|
|
111
|
+
f"-m init --dir migrations && swiftapi db upgrade --dir migrations"
|
|
112
|
+
)
|
|
113
|
+
console.print(f"启动:cd {destination} && swiftapi run --port 8000")
|
swiftapi/cli/openapi.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""`swiftapi openapi`:导出契约与前端类型。
|
|
2
|
+
|
|
3
|
+
导出的必须是**项目自己的应用**,不是内核默认应用:
|
|
4
|
+
`swiftapi openapi spec` 在项目根目录执行时自动发现 `<包名>.app:create_app`,
|
|
5
|
+
也可以用 `--app mall.app:create_app` 显式指定。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
import typer
|
|
15
|
+
from rich.console import Console
|
|
16
|
+
|
|
17
|
+
from swiftapi.cli.appref import call_factory, discover_app_reference, import_factory
|
|
18
|
+
from swiftapi.config.settings import SettingsError, load_settings
|
|
19
|
+
from swiftapi.core.docs.tsgen import generate_typescript
|
|
20
|
+
|
|
21
|
+
openapi_app = typer.Typer(help="OpenAPI 契约导出", no_args_is_help=True)
|
|
22
|
+
console = Console()
|
|
23
|
+
|
|
24
|
+
def _resolve_app(app_ref: str | None, settings_module: str | None) -> Any:
|
|
25
|
+
"""按 `--app` / 自动发现构建应用;都没找到才回落到内核默认应用。"""
|
|
26
|
+
settings = load_settings(settings_module)
|
|
27
|
+
reference = discover_app_reference(app_ref)
|
|
28
|
+
return call_factory(import_factory(reference), settings)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _build_app(app_ref: str | None, settings_module: str | None) -> Any:
|
|
32
|
+
try:
|
|
33
|
+
return _resolve_app(app_ref, settings_module)
|
|
34
|
+
except SettingsError as exc:
|
|
35
|
+
console.print(f"[red]{exc}[/red]")
|
|
36
|
+
raise typer.Exit(code=1) from exc
|
|
37
|
+
except (ImportError, AttributeError) as exc:
|
|
38
|
+
console.print(f"[red]无法加载应用工厂:{exc}[/red]")
|
|
39
|
+
console.print("用 --app <模块>:<工厂> 指定,例如 --app mall.app:create_app")
|
|
40
|
+
raise typer.Exit(code=1) from exc
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@openapi_app.command("spec")
|
|
44
|
+
def export_spec(
|
|
45
|
+
out: Path = typer.Option(Path("openapi.json"), "--out"),
|
|
46
|
+
settings: str | None = typer.Option(None, "--settings", "-s"),
|
|
47
|
+
app: str | None = typer.Option(
|
|
48
|
+
None, "--app", help="应用工厂,如 mall.app:create_app(默认自动发现)"
|
|
49
|
+
),
|
|
50
|
+
) -> None:
|
|
51
|
+
"""导出 openapi.json(提交到仓库,PR 可 diff)。"""
|
|
52
|
+
resolved = _build_app(app, settings)
|
|
53
|
+
out.write_text(json.dumps(resolved.openapi(), ensure_ascii=False, indent=2), encoding="utf-8")
|
|
54
|
+
console.print(f"[green]已导出[/green] {out}")
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
@openapi_app.command("ts")
|
|
58
|
+
def export_typescript(
|
|
59
|
+
out: Path = typer.Option(Path("clients/ts/types.ts"), "--out"),
|
|
60
|
+
settings: str | None = typer.Option(None, "--settings", "-s"),
|
|
61
|
+
app: str | None = typer.Option(
|
|
62
|
+
None, "--app", help="应用工厂,如 mall.app:create_app(默认自动发现)"
|
|
63
|
+
),
|
|
64
|
+
) -> None:
|
|
65
|
+
"""生成 TypeScript 类型(前端直接 import)。"""
|
|
66
|
+
resolved = _build_app(app, settings)
|
|
67
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
68
|
+
out.write_text(generate_typescript(resolved.openapi()), encoding="utf-8")
|
|
69
|
+
console.print(f"[green]已生成[/green] {out}")
|