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
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""工单契约。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime
|
|
6
|
+
from typing import Annotated
|
|
7
|
+
from uuid import UUID
|
|
8
|
+
|
|
9
|
+
from pydantic import Field, StringConstraints
|
|
10
|
+
|
|
11
|
+
from swiftapi.core.validation.base import OutModel, StrictModel
|
|
12
|
+
|
|
13
|
+
Subject = Annotated[str, StringConstraints(min_length=3, max_length=120)]
|
|
14
|
+
Body = Annotated[str, StringConstraints(min_length=1, max_length=5000)]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class TicketCreate(StrictModel):
|
|
18
|
+
subject: Subject
|
|
19
|
+
body: Body
|
|
20
|
+
priority: int = Field(default=2, ge=1, le=5)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class TicketUpdate(StrictModel):
|
|
24
|
+
subject: Subject | None = None
|
|
25
|
+
priority: int | None = Field(default=None, ge=1, le=5)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TicketOut(OutModel):
|
|
29
|
+
id: UUID
|
|
30
|
+
subject: str
|
|
31
|
+
status: str
|
|
32
|
+
priority: int
|
|
33
|
+
version: int
|
|
34
|
+
created_at: datetime
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class CommentCreate(StrictModel):
|
|
38
|
+
body: Body
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class CommentOut(OutModel):
|
|
42
|
+
id: UUID
|
|
43
|
+
ticket_id: UUID
|
|
44
|
+
body: str
|
|
45
|
+
created_at: datetime
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""工单用例:事务边界、授权、事件——业务只在这一层。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from uuid import UUID
|
|
6
|
+
|
|
7
|
+
from __PROJECT__.models import Comment, Ticket, TicketStatus
|
|
8
|
+
from __PROJECT__.schemas import CommentCreate, TicketCreate, TicketUpdate
|
|
9
|
+
|
|
10
|
+
from swiftapi.core.db.unit_of_work import UnitOfWork
|
|
11
|
+
from swiftapi.core.errors.base import PermissionDenied
|
|
12
|
+
from swiftapi.core.messaging.outbox import emit
|
|
13
|
+
from swiftapi.core.security.principal import Principal
|
|
14
|
+
from swiftapi.db import CRUDBase
|
|
15
|
+
|
|
16
|
+
TICKET_CREATED = "helpdesk.ticket.created"
|
|
17
|
+
TICKET_CLOSED = "helpdesk.ticket.closed"
|
|
18
|
+
COMMENT_ADDED = "helpdesk.comment.added"
|
|
19
|
+
|
|
20
|
+
TICKETS = CRUDBase(Ticket)
|
|
21
|
+
COMMENTS = CRUDBase(Comment)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class TicketNotFound(Exception):
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class TicketService:
|
|
29
|
+
def __init__(self, uow: UnitOfWork) -> None:
|
|
30
|
+
self.uow = uow
|
|
31
|
+
|
|
32
|
+
async def create(self, payload: TicketCreate, *, tenant_id: UUID, actor: Principal) -> Ticket:
|
|
33
|
+
if not actor.can("helpdesk:write"):
|
|
34
|
+
raise PermissionDenied("只有客服可以建单")
|
|
35
|
+
async with self.uow:
|
|
36
|
+
ticket = await TICKETS.create(
|
|
37
|
+
self.uow.session, payload.model_dump(), tenant_id=tenant_id
|
|
38
|
+
)
|
|
39
|
+
await emit(
|
|
40
|
+
self.uow.session,
|
|
41
|
+
TICKET_CREATED,
|
|
42
|
+
{"ticket_id": str(ticket.id), "subject": ticket.subject},
|
|
43
|
+
tenant_id=tenant_id,
|
|
44
|
+
)
|
|
45
|
+
return ticket
|
|
46
|
+
|
|
47
|
+
async def list(
|
|
48
|
+
self, *, tenant_id: UUID, status: str | None = None, limit: int = 20, offset: int = 0
|
|
49
|
+
) -> tuple[list[Ticket], int]:
|
|
50
|
+
async with self.uow:
|
|
51
|
+
filters = {"status": status} if status else None
|
|
52
|
+
return await TICKETS.list(
|
|
53
|
+
self.uow.session,
|
|
54
|
+
tenant_id=tenant_id,
|
|
55
|
+
filters=filters,
|
|
56
|
+
order_by="-created_at",
|
|
57
|
+
limit=limit,
|
|
58
|
+
offset=offset,
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
async def get(self, ticket_id: UUID, *, tenant_id: UUID) -> Ticket:
|
|
62
|
+
async with self.uow:
|
|
63
|
+
ticket = await TICKETS.get(self.uow.session, ticket_id, tenant_id=tenant_id)
|
|
64
|
+
if ticket is None:
|
|
65
|
+
raise TicketNotFound(str(ticket_id))
|
|
66
|
+
return ticket
|
|
67
|
+
|
|
68
|
+
async def update(
|
|
69
|
+
self, ticket_id: UUID, payload: TicketUpdate, *, tenant_id: UUID, actor: Principal
|
|
70
|
+
) -> Ticket:
|
|
71
|
+
if not actor.can("helpdesk:write"):
|
|
72
|
+
raise PermissionDenied("只有客服可以修改")
|
|
73
|
+
async with self.uow:
|
|
74
|
+
ticket = await TICKETS.get(self.uow.session, ticket_id, tenant_id=tenant_id)
|
|
75
|
+
if ticket is None:
|
|
76
|
+
raise TicketNotFound(str(ticket_id))
|
|
77
|
+
await TICKETS.update(self.uow.session, ticket, payload)
|
|
78
|
+
return ticket
|
|
79
|
+
|
|
80
|
+
async def close(self, ticket_id: UUID, *, tenant_id: UUID, actor: Principal) -> Ticket:
|
|
81
|
+
if not actor.can("helpdesk:write"):
|
|
82
|
+
raise PermissionDenied("只有客服可以关单")
|
|
83
|
+
async with self.uow:
|
|
84
|
+
ticket = await TICKETS.get(self.uow.session, ticket_id, tenant_id=tenant_id)
|
|
85
|
+
if ticket is None:
|
|
86
|
+
raise TicketNotFound(str(ticket_id))
|
|
87
|
+
ticket.status = TicketStatus.CLOSED.value
|
|
88
|
+
await self.uow.session.flush()
|
|
89
|
+
await emit(
|
|
90
|
+
self.uow.session, TICKET_CLOSED, {"ticket_id": str(ticket.id)}, tenant_id=tenant_id
|
|
91
|
+
)
|
|
92
|
+
return ticket
|
|
93
|
+
|
|
94
|
+
async def add_comment(
|
|
95
|
+
self, ticket_id: UUID, payload: CommentCreate, *, tenant_id: UUID, actor: Principal
|
|
96
|
+
) -> Comment:
|
|
97
|
+
if not actor.can("helpdesk:comment") and not actor.can("helpdesk:write"):
|
|
98
|
+
raise PermissionDenied("无权评论")
|
|
99
|
+
async with self.uow:
|
|
100
|
+
ticket = await TICKETS.get(self.uow.session, ticket_id, tenant_id=tenant_id)
|
|
101
|
+
if ticket is None:
|
|
102
|
+
raise TicketNotFound(str(ticket_id))
|
|
103
|
+
comment = await COMMENTS.create(
|
|
104
|
+
self.uow.session,
|
|
105
|
+
{"ticket_id": ticket_id, "author_id": actor.subject, "body": payload.body},
|
|
106
|
+
tenant_id=tenant_id,
|
|
107
|
+
)
|
|
108
|
+
await emit(
|
|
109
|
+
self.uow.session,
|
|
110
|
+
COMMENT_ADDED,
|
|
111
|
+
{"ticket_id": str(ticket_id), "comment_id": str(comment.id)},
|
|
112
|
+
tenant_id=tenant_id,
|
|
113
|
+
)
|
|
114
|
+
return comment
|
|
115
|
+
|
|
116
|
+
async def list_comments(self, ticket_id: UUID, *, tenant_id: UUID) -> list[Comment]:
|
|
117
|
+
async with self.uow:
|
|
118
|
+
rows, _ = await COMMENTS.list(
|
|
119
|
+
self.uow.session,
|
|
120
|
+
tenant_id=tenant_id,
|
|
121
|
+
filters={"ticket_id": ticket_id},
|
|
122
|
+
order_by="created_at",
|
|
123
|
+
limit=100,
|
|
124
|
+
)
|
|
125
|
+
return rows
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""项目配置(`swiftapi new project` 布局):不写在内核里。"""
|
|
2
|
+
|
|
3
|
+
settings = {
|
|
4
|
+
"app": {"name": "__PROJECT__", "env": "dev"},
|
|
5
|
+
"server": {"max_request_body_bytes": 6 * 1024 * 1024},
|
|
6
|
+
"database": {"url": "sqlite+aiosqlite:///./__PROJECT__.db"},
|
|
7
|
+
"tenant": {"enabled": True, "resolver": ["jwt", "header"], "default_slug": "acme"},
|
|
8
|
+
"security": {
|
|
9
|
+
"jwt_algorithm": "HS256",
|
|
10
|
+
"jwt_private_key": "__PROJECT__-dev-secret-please-rotate-32",
|
|
11
|
+
"allow_insecure": True, # 仅开发;生产强制 RS256
|
|
12
|
+
},
|
|
13
|
+
"admin": {"enabled": True},
|
|
14
|
+
"uploads": {"max_bytes": 5 * 1024 * 1024},
|
|
15
|
+
"docs": {"enabled": True, "title": "Helpdesk API"},
|
|
16
|
+
"observability": {"log_level": "INFO", "log_format": "console"},
|
|
17
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# __PROJECT__
|
|
2
|
+
|
|
3
|
+
由 `swift-api startproject __PROJECT__` 生成。
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
# 建表(先在 apps/<app>/model/ 加模型,并在 __PROJECT__/models.py 里 import)
|
|
7
|
+
swift-api db revision --models __PROJECT__.models -m init --dir migrations
|
|
8
|
+
swift-api db upgrade --dir migrations
|
|
9
|
+
|
|
10
|
+
# 启动(自动发现项目应用)
|
|
11
|
+
swiftapi run --port 8001
|
|
12
|
+
# 或
|
|
13
|
+
python start.py --reload
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
- 文档 <http://127.0.0.1:8001/docs>
|
|
17
|
+
- 后台 <http://127.0.0.1:8001/admin>
|
|
18
|
+
|
|
19
|
+
首个后台账号(Web 不开放注册):
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
swiftapi admin create-user -u admin -p '换成强口令'
|
|
23
|
+
# 在项目根目录可省略 -s(自动发现 conf/settings.py)
|
|
24
|
+
```
|
|
25
|
+
- 新增应用:`swift-api startapp <name>`(默认建在 `apps/` 下)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""__PROJECT__ 项目包。"""
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""ASGI 入口:引入 conf 中的配置并装配应用。
|
|
2
|
+
|
|
3
|
+
uvicorn --factory __PROJECT__.app:create_app
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from __PROJECT__ import models # noqa: F401 - 导入即注册全部 ORM 模型
|
|
9
|
+
from swiftapi.app.factory import build_app
|
|
10
|
+
from swiftapi.config.settings import Settings, load_settings
|
|
11
|
+
from swiftapi.core.http import App
|
|
12
|
+
|
|
13
|
+
from __PROJECT__.router import api_router
|
|
14
|
+
|
|
15
|
+
SETTINGS_MODULE = "__PROJECT__.conf.settings"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def create_app(settings: Settings | None = None) -> App:
|
|
19
|
+
resolved = settings or load_settings(SETTINGS_MODULE)
|
|
20
|
+
app = build_app(
|
|
21
|
+
resolved,
|
|
22
|
+
include_builtin_modules=False, # 项目自己的业务走 apps/
|
|
23
|
+
extra_routers=(),
|
|
24
|
+
)
|
|
25
|
+
app.include_router(api_router)
|
|
26
|
+
return app
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""业务应用集合:每个子包 = 一个 app(api/crud/model/schema/service)。"""
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""配置包:只放配置,不放业务。"""
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""项目配置(Django 风格):`SWIFTAPI_SETTINGS_MODULE=__PROJECT__.conf.settings`。
|
|
2
|
+
|
|
3
|
+
优先级:显式传参 > 环境变量 `SWIFTAPI__*` > .env > 本文件 > 内核默认。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
settings = {
|
|
9
|
+
"app": {"name": "__PROJECT__", "env": "dev"},
|
|
10
|
+
"server": {
|
|
11
|
+
"host": "127.0.0.1",
|
|
12
|
+
"port": 8001,
|
|
13
|
+
"workers": 1,
|
|
14
|
+
"max_request_body_bytes": 6 * 1024 * 1024, # 必须 >= uploads.max_bytes
|
|
15
|
+
},
|
|
16
|
+
"database": {"url": "sqlite+aiosqlite:///./__PROJECT__.db"},
|
|
17
|
+
# Outbox 中继:业务事件写进 outbox 表后,由 lifespan 周期投递到总线。
|
|
18
|
+
# 单实例开发用进程内总线即可;多副本生产换 redis_streams/rabbitmq。
|
|
19
|
+
"messaging": {
|
|
20
|
+
"enabled": False,
|
|
21
|
+
"backend": "inprocess",
|
|
22
|
+
"outbox_relay_enabled": False,
|
|
23
|
+
"outbox_relay_interval_s": 1.0,
|
|
24
|
+
},
|
|
25
|
+
"tenant": {"enabled": False},
|
|
26
|
+
"docs": {"enabled": True, "title": "__PROJECT__ API"},
|
|
27
|
+
"security": {
|
|
28
|
+
"jwt_algorithm": "HS256",
|
|
29
|
+
"jwt_private_key": "__PROJECT__-dev-secret-please-rotate-32",
|
|
30
|
+
"allow_insecure": True, # 生产必须 RS256
|
|
31
|
+
},
|
|
32
|
+
"admin": {
|
|
33
|
+
"enabled": True,
|
|
34
|
+
"throttle_prune_enabled": True, # 进程内定时清理登录节流表
|
|
35
|
+
"throttle_prune_interval_s": 21600, # 6 小时
|
|
36
|
+
"throttle_retention_s": 86400, # 保留 1 天
|
|
37
|
+
},
|
|
38
|
+
"uploads": {
|
|
39
|
+
"enabled": True,
|
|
40
|
+
"max_bytes": 5 * 1024 * 1024,
|
|
41
|
+
"max_parts": 10,
|
|
42
|
+
"allowed_types": ["image/png", "image/jpeg", "application/pdf"],
|
|
43
|
+
"streaming": True,
|
|
44
|
+
"scan_timeout_s": 5.0,
|
|
45
|
+
},
|
|
46
|
+
"outbound": {
|
|
47
|
+
"allow_private": False, # SSRF:默认禁止访问内网/元数据
|
|
48
|
+
"allowed_hosts": [], # 例:["api.stripe.com"]
|
|
49
|
+
"check_dns": True,
|
|
50
|
+
"timeout_s": 2.0,
|
|
51
|
+
},
|
|
52
|
+
"observability": {
|
|
53
|
+
"log_level": "INFO",
|
|
54
|
+
"log_format": "console", # 控制台人读;落盘始终 JSON
|
|
55
|
+
"log_to_file": True, # app/access/crud/error 四路分文件
|
|
56
|
+
"log_dir": "logs",
|
|
57
|
+
"log_max_bytes": 10 * 1024 * 1024,
|
|
58
|
+
"log_backup_count": 5,
|
|
59
|
+
"log_sql": True, # 执行过的 SQL 落到 logs/sql.log(不含参数值)
|
|
60
|
+
"log_sql_max_chars": 2000,
|
|
61
|
+
# 每 7 天把 logs/ 压缩到 logs/archive/YYYYmmddHHMMSS.zip,然后清空原日志
|
|
62
|
+
"log_archive_enabled": True,
|
|
63
|
+
"log_archive_dir": "logs/archive",
|
|
64
|
+
"log_archive_interval_days": 7,
|
|
65
|
+
# 请求体采样日志(默认 5%,落盘前脱敏)
|
|
66
|
+
"log_request_body": True,
|
|
67
|
+
"log_request_body_sample_ratio": 0.05,
|
|
68
|
+
"log_request_body_max_per_minute": 600, # 集群预算/分钟,0=不限
|
|
69
|
+
"log_request_body_replicas": 1, # 副本数:预算按它均摊
|
|
70
|
+
# 业务自定义脱敏字段(叠加在内置列表上,大小写不敏感)
|
|
71
|
+
"log_mask_keys": ["身份证号", "bankAccount"],
|
|
72
|
+
},
|
|
73
|
+
}
|
|
File without changes
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""领域模型入口:新增模型后在这里导入(迁移只扫已导入的模型)。
|
|
2
|
+
|
|
3
|
+
swiftapi db revision --models __PROJECT__.models -m "add model" --dir migrations
|
|
4
|
+
|
|
5
|
+
为什么需要这个文件:SQLAlchemy 的 metadata 只包含"已经被 import 过"的模型。
|
|
6
|
+
忘记导入不会报错,只会少建一张表——这是最难排查的一类事故。
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
# 新增模型后在这里加一行,例如:
|
|
12
|
+
# from __PROJECT__.apps.orders.model.order import Order # noqa: F401
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# 反向代理示例:超时预算必须大于应用侧 request_timeout_s
|
|
2
|
+
upstream __PROJECT__ {
|
|
3
|
+
server 127.0.0.1:8001;
|
|
4
|
+
keepalive 32;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
server {
|
|
8
|
+
listen 80;
|
|
9
|
+
server_name _;
|
|
10
|
+
|
|
11
|
+
location / {
|
|
12
|
+
proxy_pass http://__PROJECT__;
|
|
13
|
+
proxy_http_version 1.1;
|
|
14
|
+
proxy_set_header Connection "";
|
|
15
|
+
proxy_set_header Host $host;
|
|
16
|
+
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
|
17
|
+
proxy_connect_timeout 2s;
|
|
18
|
+
proxy_read_timeout 15s;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""蓝图路由:项目级 → 应用级 → 接口级(三级管理)。
|
|
2
|
+
|
|
3
|
+
- 项目级(本文件):`/api/v1` + 按 app 名挂载;
|
|
4
|
+
- 应用级(`<dir>/<app>/router.py`):聚合该 app 的 `api/*.py`;
|
|
5
|
+
- 接口级(`<dir>/<app>/api/*.py`):每个文件一个 `router`。
|
|
6
|
+
|
|
7
|
+
`swift-api startapp` 生成目录后会自动登记到 `APP_DIRS`,不需要手改本文件。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import importlib
|
|
13
|
+
import pkgutil
|
|
14
|
+
|
|
15
|
+
from swiftapi.core.http import Router
|
|
16
|
+
|
|
17
|
+
API_PREFIX = "/api/v1"
|
|
18
|
+
APP_DIRS: tuple[str, ...] = ("apps",)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def load_app_routers() -> list[tuple[str, Router]]:
|
|
22
|
+
"""扫描 APP_DIRS 下每个包,取其中的 `router`。"""
|
|
23
|
+
found: list[tuple[str, Router]] = []
|
|
24
|
+
for directory in APP_DIRS:
|
|
25
|
+
try:
|
|
26
|
+
package = importlib.import_module(f"__PROJECT__.{directory}")
|
|
27
|
+
except ModuleNotFoundError:
|
|
28
|
+
continue
|
|
29
|
+
for info in pkgutil.iter_modules(package.__path__):
|
|
30
|
+
if info.name.startswith("_"):
|
|
31
|
+
continue
|
|
32
|
+
try:
|
|
33
|
+
module = importlib.import_module(f"__PROJECT__.{directory}.{info.name}.router")
|
|
34
|
+
except ModuleNotFoundError:
|
|
35
|
+
continue
|
|
36
|
+
router = getattr(module, "router", None)
|
|
37
|
+
if isinstance(router, Router):
|
|
38
|
+
found.append((info.name, router))
|
|
39
|
+
return found
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
api_router = Router(prefix=API_PREFIX)
|
|
43
|
+
for _name, _router in load_app_routers():
|
|
44
|
+
api_router.include_router(_router, prefix=f"/{_name}")
|
|
45
|
+
|
|
46
|
+
__all__ = ["API_PREFIX", "APP_DIRS", "api_router", "load_app_routers"]
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
# 生产启动示例:worker 数按 CPU 核数给(SQLite 单写者,默认 1)
|
|
3
|
+
set -euo pipefail
|
|
4
|
+
|
|
5
|
+
# 固定工作目录到项目根:配置里的相对路径(sqlite 文件、logs/)才稳定。
|
|
6
|
+
# 项目包在上一级目录,用 --app-dir 让 `__PROJECT__` 可导入。
|
|
7
|
+
PROJECT_ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
|
8
|
+
cd "$PROJECT_ROOT"
|
|
9
|
+
|
|
10
|
+
# 用 `python -m uvicorn` 而不是裸 `uvicorn`:没激活 venv 时也能用 PYTHON 指定解释器
|
|
11
|
+
exec "${PYTHON:-python}" -m uvicorn --factory __PROJECT__.app:create_app \
|
|
12
|
+
--app-dir "$PROJECT_ROOT/.." \
|
|
13
|
+
--host 0.0.0.0 --port "${PORT:-8001}" --workers "${WORKERS:-1}"
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""开发启动脚本:python start.py [--reload] [--port 8001]"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
# 项目包名就是本目录名,父目录才是导入根。
|
|
10
|
+
# 不插入这一行时,在项目根目录执行 `python start.py` 会报 No module named '__PROJECT__'
|
|
11
|
+
# (真实踩过:README 让用户这么启动)。
|
|
12
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
13
|
+
|
|
14
|
+
import uvicorn # noqa: E402
|
|
15
|
+
|
|
16
|
+
from __PROJECT__.conf.settings import settings # noqa: E402
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def main() -> None:
|
|
20
|
+
parser = argparse.ArgumentParser()
|
|
21
|
+
parser.add_argument("--host", default=settings["server"]["host"])
|
|
22
|
+
parser.add_argument("--port", type=int, default=settings["server"]["port"])
|
|
23
|
+
parser.add_argument("--reload", action="store_true")
|
|
24
|
+
args = parser.parse_args()
|
|
25
|
+
uvicorn.run(
|
|
26
|
+
"__PROJECT__.app:create_app",
|
|
27
|
+
factory=True,
|
|
28
|
+
host=args.host,
|
|
29
|
+
port=args.port,
|
|
30
|
+
reload=args.reload,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
if __name__ == "__main__":
|
|
35
|
+
main()
|