sisyo 1.7.0 → 1.8.0
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.
- package/LICENSE +16 -16
- package/README.md +167 -166
- package/bin/known-hashes.json +6 -1
- package/bin/sisyo.js +285 -285
- package/package.json +30 -30
- package/templates/.claude/rules/agents-and-tests.md +32 -24
- package/templates/.claude/rules/docs.md +19 -19
- package/templates/.claude/skills/fastapi-best-practices/ASYNC-PATTERNS.md +121 -121
- package/templates/.claude/skills/fastapi-best-practices/DATABASE.md +153 -153
- package/templates/.claude/skills/fastapi-best-practices/DEPENDENCIES.md +140 -140
- package/templates/.claude/skills/fastapi-best-practices/PROJECT-STRUCTURE.md +90 -90
- package/templates/.claude/skills/fastapi-best-practices/PYDANTIC-GUIDE.md +155 -155
- package/templates/.claude/skills/fastapi-best-practices/SKILL.md +123 -123
- package/templates/.claude/skills/g6-style/SKILL.md +125 -125
- package/templates/.claude/skills/g6-style/references/checks.md +58 -58
- package/templates/.claude/skills/g6-style/references/imagery.md +103 -103
- package/templates/.claude/skills/g6-style/references/motion.md +121 -121
- package/templates/.claude/skills/g6-style/references/sections.md +263 -263
- package/templates/.claude/skills/g6-style/references/tokens.md +197 -197
- package/templates/.claude/skills/hindsight/SKILL.md +175 -175
- package/templates/.claude/skills/hoang-auth/SKILL.md +188 -0
- package/templates/.claude/skills/html-docs/SKILL.md +207 -207
- package/templates/.claude/skills/i18n-multilang/SKILL.md +153 -153
- package/templates/.claude/skills/i18n-multilang/assets/languages.json +47 -47
- package/templates/.claude/skills/i18n-multilang/assets/plural-vectors.json +46 -46
- package/templates/.claude/skills/i18n-multilang/assets/project/README.md +17 -17
- package/templates/.claude/skills/i18n-multilang/assets/project/gitattributes.txt +6 -6
- package/templates/.claude/skills/i18n-multilang/assets/project/gitignore.txt +4 -4
- package/templates/.claude/skills/i18n-multilang/assets/project/glossary.json +6 -6
- package/templates/.claude/skills/i18n-multilang/assets/project/i18n.config.json +22 -22
- package/templates/.claude/skills/i18n-multilang/assets/project/locales/__source__/common.json +10 -10
- package/templates/.claude/skills/i18n-multilang/assets/project/notes/common.json +5 -5
- package/templates/.claude/skills/i18n-multilang/assets/project/style.md +20 -20
- package/templates/.claude/skills/i18n-multilang/references/format.md +100 -100
- package/templates/.claude/skills/i18n-multilang/references/languages.md +97 -97
- package/templates/.claude/skills/i18n-multilang/references/layout-and-versioning.md +256 -256
- package/templates/.claude/skills/i18n-multilang/references/numbers.md +161 -161
- package/templates/.claude/skills/i18n-multilang/references/platform-unity.md +142 -142
- package/templates/.claude/skills/i18n-multilang/references/platform-web.md +107 -107
- package/templates/.claude/skills/i18n-multilang/references/translation.md +143 -143
- package/templates/.claude/skills/i18n-multilang/references/voice.md +271 -271
- package/templates/.claude/skills/i18n-multilang/scripts/i18n.py +1041 -1041
- package/templates/.claude/skills/i18n-multilang/scripts/numwords.py +1013 -1013
- package/templates/.claude/skills/i18n-multilang/scripts/voice.py +478 -478
- package/templates/.claude/skills/neon-game-ui-ux-skill/COMPONENTS.md +490 -490
- package/templates/.claude/skills/neon-game-ui-ux-skill/GAMIFICATION.md +246 -246
- package/templates/.claude/skills/neon-game-ui-ux-skill/ICONS.md +249 -249
- package/templates/.claude/skills/neon-game-ui-ux-skill/LAYOUT-NAV.md +362 -362
- package/templates/.claude/skills/neon-game-ui-ux-skill/MOTION-A11Y.md +168 -168
- package/templates/.claude/skills/neon-game-ui-ux-skill/SKILL.md +137 -137
- package/templates/.claude/skills/neon-game-ui-ux-skill/TOKENS.md +323 -323
- package/templates/.claude/skills/react-page-oriented/SKILL.md +407 -407
- package/templates/.claude/skills/react-page-oriented/triggers.md +12 -12
- package/templates/.claude/skills/terraform-best-practices/SKILL.md +341 -341
- package/templates/.claude/skills/typesafe-jev/SKILL.md +148 -148
- package/templates/.claude/skills/vibe-docs/SKILL.md +242 -242
- package/templates/SISYO.md +37 -37
- package/templates/docs/99_progress/features.md +7 -7
- package/templates/docs/99_progress/handoff.md +19 -19
- package/templates/docs/99_progress/todo.md +15 -15
- package/templates/docs/MAP.md +26 -26
|
@@ -1,155 +1,155 @@
|
|
|
1
|
-
# Pydantic Guide
|
|
2
|
-
|
|
3
|
-
## Schema Design
|
|
4
|
-
|
|
5
|
-
### Request Validation
|
|
6
|
-
|
|
7
|
-
```python
|
|
8
|
-
from enum import StrEnum
|
|
9
|
-
from pydantic import BaseModel, Field, EmailStr, AnyUrl, field_validator
|
|
10
|
-
import re
|
|
11
|
-
|
|
12
|
-
class UserRole(StrEnum):
|
|
13
|
-
ADMIN = "admin"
|
|
14
|
-
USER = "user"
|
|
15
|
-
GUEST = "guest"
|
|
16
|
-
|
|
17
|
-
class UserCreate(BaseModel):
|
|
18
|
-
username: str = Field(min_length=1, max_length=128, pattern="^[A-Za-z0-9-_]+$")
|
|
19
|
-
email: EmailStr
|
|
20
|
-
age: int | None = Field(ge=18, default=None)
|
|
21
|
-
role: UserRole = UserRole.USER
|
|
22
|
-
website: AnyUrl | None = None
|
|
23
|
-
|
|
24
|
-
@field_validator("username")
|
|
25
|
-
@classmethod
|
|
26
|
-
def username_lowercase(cls, v: str) -> str:
|
|
27
|
-
return v.lower()
|
|
28
|
-
```
|
|
29
|
-
|
|
30
|
-
### Password Validation
|
|
31
|
-
|
|
32
|
-
```python
|
|
33
|
-
STRONG_PASSWORD_PATTERN = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
|
|
34
|
-
|
|
35
|
-
class UserCreate(BaseModel):
|
|
36
|
-
password: str
|
|
37
|
-
|
|
38
|
-
@field_validator("password")
|
|
39
|
-
@classmethod
|
|
40
|
-
def validate_password(cls, v: str) -> str:
|
|
41
|
-
if not re.match(STRONG_PASSWORD_PATTERN, v):
|
|
42
|
-
raise ValueError(
|
|
43
|
-
"Password must contain at least one lowercase, "
|
|
44
|
-
"one uppercase, one digit, and one special character"
|
|
45
|
-
)
|
|
46
|
-
return v
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
## Custom Base Model
|
|
50
|
-
|
|
51
|
-
```python
|
|
52
|
-
from datetime import datetime
|
|
53
|
-
from zoneinfo import ZoneInfo
|
|
54
|
-
from pydantic import BaseModel, ConfigDict
|
|
55
|
-
from fastapi.encoders import jsonable_encoder
|
|
56
|
-
|
|
57
|
-
def datetime_to_gmt_str(dt: datetime) -> str:
|
|
58
|
-
if not dt.tzinfo:
|
|
59
|
-
dt = dt.replace(tzinfo=ZoneInfo("UTC"))
|
|
60
|
-
return dt.strftime("%Y-%m-%dT%H:%M:%S%z")
|
|
61
|
-
|
|
62
|
-
class CustomModel(BaseModel):
|
|
63
|
-
model_config = ConfigDict(
|
|
64
|
-
json_encoders={datetime: datetime_to_gmt_str},
|
|
65
|
-
populate_by_name=True,
|
|
66
|
-
from_attributes=True, # for ORM mode
|
|
67
|
-
)
|
|
68
|
-
|
|
69
|
-
def serializable_dict(self, **kwargs):
|
|
70
|
-
"""Return dict with only serializable fields."""
|
|
71
|
-
return jsonable_encoder(self.model_dump())
|
|
72
|
-
```
|
|
73
|
-
|
|
74
|
-
## Settings Management
|
|
75
|
-
|
|
76
|
-
Split settings by domain:
|
|
77
|
-
|
|
78
|
-
```python
|
|
79
|
-
# src/auth/config.py
|
|
80
|
-
from pydantic_settings import BaseSettings
|
|
81
|
-
|
|
82
|
-
class AuthConfig(BaseSettings):
|
|
83
|
-
JWT_ALG: str = "HS256"
|
|
84
|
-
JWT_SECRET: str
|
|
85
|
-
JWT_EXP: int = 5 # minutes
|
|
86
|
-
REFRESH_TOKEN_EXP: int = 60 * 24 * 30 # 30 days
|
|
87
|
-
SECURE_COOKIES: bool = True
|
|
88
|
-
|
|
89
|
-
auth_settings = AuthConfig()
|
|
90
|
-
|
|
91
|
-
# src/config.py
|
|
92
|
-
from pydantic import PostgresDsn, RedisDsn
|
|
93
|
-
from pydantic_settings import BaseSettings
|
|
94
|
-
|
|
95
|
-
class Config(BaseSettings):
|
|
96
|
-
DATABASE_URL: PostgresDsn
|
|
97
|
-
REDIS_URL: RedisDsn | None = None
|
|
98
|
-
ENVIRONMENT: str = "production"
|
|
99
|
-
CORS_ORIGINS: list[str] = []
|
|
100
|
-
|
|
101
|
-
settings = Config()
|
|
102
|
-
```
|
|
103
|
-
|
|
104
|
-
## Response Models
|
|
105
|
-
|
|
106
|
-
```python
|
|
107
|
-
# Separate input/output schemas
|
|
108
|
-
class UserCreate(BaseModel):
|
|
109
|
-
username: str
|
|
110
|
-
email: EmailStr
|
|
111
|
-
password: str
|
|
112
|
-
|
|
113
|
-
class UserResponse(BaseModel):
|
|
114
|
-
id: UUID4
|
|
115
|
-
username: str
|
|
116
|
-
email: EmailStr
|
|
117
|
-
created_at: datetime
|
|
118
|
-
|
|
119
|
-
model_config = ConfigDict(from_attributes=True)
|
|
120
|
-
|
|
121
|
-
class UserInDB(UserResponse):
|
|
122
|
-
hashed_password: str # internal only, never expose
|
|
123
|
-
```
|
|
124
|
-
|
|
125
|
-
## Nested Objects
|
|
126
|
-
|
|
127
|
-
```python
|
|
128
|
-
class Author(BaseModel):
|
|
129
|
-
id: UUID4
|
|
130
|
-
name: str
|
|
131
|
-
|
|
132
|
-
class PostResponse(BaseModel):
|
|
133
|
-
id: UUID4
|
|
134
|
-
title: str
|
|
135
|
-
author: Author # nested object
|
|
136
|
-
tags: list[str] = []
|
|
137
|
-
```
|
|
138
|
-
|
|
139
|
-
## Validation Error Messages
|
|
140
|
-
|
|
141
|
-
ValueError in Pydantic schemas becomes 422 Unprocessable Entity:
|
|
142
|
-
|
|
143
|
-
```python
|
|
144
|
-
class ProfileCreate(BaseModel):
|
|
145
|
-
username: str
|
|
146
|
-
|
|
147
|
-
@field_validator("username")
|
|
148
|
-
@classmethod
|
|
149
|
-
def validate_username(cls, v: str) -> str:
|
|
150
|
-
if v.lower() in ["admin", "root", "system"]:
|
|
151
|
-
raise ValueError("Username is reserved")
|
|
152
|
-
return v
|
|
153
|
-
|
|
154
|
-
# Response: {"detail": [{"loc": ["body", "username"], "msg": "Username is reserved", "type": "value_error"}]}
|
|
155
|
-
```
|
|
1
|
+
# Pydantic Guide
|
|
2
|
+
|
|
3
|
+
## Schema Design
|
|
4
|
+
|
|
5
|
+
### Request Validation
|
|
6
|
+
|
|
7
|
+
```python
|
|
8
|
+
from enum import StrEnum
|
|
9
|
+
from pydantic import BaseModel, Field, EmailStr, AnyUrl, field_validator
|
|
10
|
+
import re
|
|
11
|
+
|
|
12
|
+
class UserRole(StrEnum):
|
|
13
|
+
ADMIN = "admin"
|
|
14
|
+
USER = "user"
|
|
15
|
+
GUEST = "guest"
|
|
16
|
+
|
|
17
|
+
class UserCreate(BaseModel):
|
|
18
|
+
username: str = Field(min_length=1, max_length=128, pattern="^[A-Za-z0-9-_]+$")
|
|
19
|
+
email: EmailStr
|
|
20
|
+
age: int | None = Field(ge=18, default=None)
|
|
21
|
+
role: UserRole = UserRole.USER
|
|
22
|
+
website: AnyUrl | None = None
|
|
23
|
+
|
|
24
|
+
@field_validator("username")
|
|
25
|
+
@classmethod
|
|
26
|
+
def username_lowercase(cls, v: str) -> str:
|
|
27
|
+
return v.lower()
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### Password Validation
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
STRONG_PASSWORD_PATTERN = r"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
|
|
34
|
+
|
|
35
|
+
class UserCreate(BaseModel):
|
|
36
|
+
password: str
|
|
37
|
+
|
|
38
|
+
@field_validator("password")
|
|
39
|
+
@classmethod
|
|
40
|
+
def validate_password(cls, v: str) -> str:
|
|
41
|
+
if not re.match(STRONG_PASSWORD_PATTERN, v):
|
|
42
|
+
raise ValueError(
|
|
43
|
+
"Password must contain at least one lowercase, "
|
|
44
|
+
"one uppercase, one digit, and one special character"
|
|
45
|
+
)
|
|
46
|
+
return v
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Custom Base Model
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from datetime import datetime
|
|
53
|
+
from zoneinfo import ZoneInfo
|
|
54
|
+
from pydantic import BaseModel, ConfigDict
|
|
55
|
+
from fastapi.encoders import jsonable_encoder
|
|
56
|
+
|
|
57
|
+
def datetime_to_gmt_str(dt: datetime) -> str:
|
|
58
|
+
if not dt.tzinfo:
|
|
59
|
+
dt = dt.replace(tzinfo=ZoneInfo("UTC"))
|
|
60
|
+
return dt.strftime("%Y-%m-%dT%H:%M:%S%z")
|
|
61
|
+
|
|
62
|
+
class CustomModel(BaseModel):
|
|
63
|
+
model_config = ConfigDict(
|
|
64
|
+
json_encoders={datetime: datetime_to_gmt_str},
|
|
65
|
+
populate_by_name=True,
|
|
66
|
+
from_attributes=True, # for ORM mode
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
def serializable_dict(self, **kwargs):
|
|
70
|
+
"""Return dict with only serializable fields."""
|
|
71
|
+
return jsonable_encoder(self.model_dump())
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Settings Management
|
|
75
|
+
|
|
76
|
+
Split settings by domain:
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
# src/auth/config.py
|
|
80
|
+
from pydantic_settings import BaseSettings
|
|
81
|
+
|
|
82
|
+
class AuthConfig(BaseSettings):
|
|
83
|
+
JWT_ALG: str = "HS256"
|
|
84
|
+
JWT_SECRET: str
|
|
85
|
+
JWT_EXP: int = 5 # minutes
|
|
86
|
+
REFRESH_TOKEN_EXP: int = 60 * 24 * 30 # 30 days
|
|
87
|
+
SECURE_COOKIES: bool = True
|
|
88
|
+
|
|
89
|
+
auth_settings = AuthConfig()
|
|
90
|
+
|
|
91
|
+
# src/config.py
|
|
92
|
+
from pydantic import PostgresDsn, RedisDsn
|
|
93
|
+
from pydantic_settings import BaseSettings
|
|
94
|
+
|
|
95
|
+
class Config(BaseSettings):
|
|
96
|
+
DATABASE_URL: PostgresDsn
|
|
97
|
+
REDIS_URL: RedisDsn | None = None
|
|
98
|
+
ENVIRONMENT: str = "production"
|
|
99
|
+
CORS_ORIGINS: list[str] = []
|
|
100
|
+
|
|
101
|
+
settings = Config()
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Response Models
|
|
105
|
+
|
|
106
|
+
```python
|
|
107
|
+
# Separate input/output schemas
|
|
108
|
+
class UserCreate(BaseModel):
|
|
109
|
+
username: str
|
|
110
|
+
email: EmailStr
|
|
111
|
+
password: str
|
|
112
|
+
|
|
113
|
+
class UserResponse(BaseModel):
|
|
114
|
+
id: UUID4
|
|
115
|
+
username: str
|
|
116
|
+
email: EmailStr
|
|
117
|
+
created_at: datetime
|
|
118
|
+
|
|
119
|
+
model_config = ConfigDict(from_attributes=True)
|
|
120
|
+
|
|
121
|
+
class UserInDB(UserResponse):
|
|
122
|
+
hashed_password: str # internal only, never expose
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## Nested Objects
|
|
126
|
+
|
|
127
|
+
```python
|
|
128
|
+
class Author(BaseModel):
|
|
129
|
+
id: UUID4
|
|
130
|
+
name: str
|
|
131
|
+
|
|
132
|
+
class PostResponse(BaseModel):
|
|
133
|
+
id: UUID4
|
|
134
|
+
title: str
|
|
135
|
+
author: Author # nested object
|
|
136
|
+
tags: list[str] = []
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Validation Error Messages
|
|
140
|
+
|
|
141
|
+
ValueError in Pydantic schemas becomes 422 Unprocessable Entity:
|
|
142
|
+
|
|
143
|
+
```python
|
|
144
|
+
class ProfileCreate(BaseModel):
|
|
145
|
+
username: str
|
|
146
|
+
|
|
147
|
+
@field_validator("username")
|
|
148
|
+
@classmethod
|
|
149
|
+
def validate_username(cls, v: str) -> str:
|
|
150
|
+
if v.lower() in ["admin", "root", "system"]:
|
|
151
|
+
raise ValueError("Username is reserved")
|
|
152
|
+
return v
|
|
153
|
+
|
|
154
|
+
# Response: {"detail": [{"loc": ["body", "username"], "msg": "Username is reserved", "type": "value_error"}]}
|
|
155
|
+
```
|
|
@@ -1,123 +1,123 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: fastapi-best-practices
|
|
3
|
-
description: FastAPI project structure, async patterns, Pydantic schemas, dependency injection, and database patterns. Use when building FastAPI backends, creating REST APIs, or reviewing Python web service code.
|
|
4
|
-
---
|
|
5
|
-
|
|
6
|
-
# FastAPI Best Practices
|
|
7
|
-
|
|
8
|
-
## Quick Start
|
|
9
|
-
|
|
10
|
-
```python
|
|
11
|
-
# Domain-based structure (recommended for scalable projects)
|
|
12
|
-
src/
|
|
13
|
-
├── auth/
|
|
14
|
-
│ ├── router.py # endpoints
|
|
15
|
-
│ ├── schemas.py # pydantic models
|
|
16
|
-
│ ├── models.py # db models
|
|
17
|
-
│ ├── service.py # business logic
|
|
18
|
-
│ ├── dependencies.py
|
|
19
|
-
│ └── exceptions.py
|
|
20
|
-
├── posts/
|
|
21
|
-
│ └── ...
|
|
22
|
-
├── config.py # global config
|
|
23
|
-
├── database.py # db connection
|
|
24
|
-
└── main.py # FastAPI app init
|
|
25
|
-
```
|
|
26
|
-
|
|
27
|
-
## Core Principles
|
|
28
|
-
|
|
29
|
-
### 1. Async Routes Done Right
|
|
30
|
-
|
|
31
|
-
```python
|
|
32
|
-
# BAD - blocks event loop
|
|
33
|
-
@router.get("/bad")
|
|
34
|
-
async def bad_route():
|
|
35
|
-
time.sleep(10) # blocks everything!
|
|
36
|
-
return {"ok": True}
|
|
37
|
-
|
|
38
|
-
# GOOD - sync route runs in threadpool
|
|
39
|
-
@router.get("/good")
|
|
40
|
-
def good_route():
|
|
41
|
-
time.sleep(10) # runs in separate thread
|
|
42
|
-
return {"ok": True}
|
|
43
|
-
|
|
44
|
-
# BEST - truly async
|
|
45
|
-
@router.get("/best")
|
|
46
|
-
async def best_route():
|
|
47
|
-
await asyncio.sleep(10) # non-blocking
|
|
48
|
-
return {"ok": True}
|
|
49
|
-
```
|
|
50
|
-
|
|
51
|
-
### 2. Pydantic Validation
|
|
52
|
-
|
|
53
|
-
```python
|
|
54
|
-
from pydantic import BaseModel, Field, EmailStr
|
|
55
|
-
|
|
56
|
-
class UserCreate(BaseModel):
|
|
57
|
-
username: str = Field(min_length=1, max_length=128, pattern="^[A-Za-z0-9-_]+$")
|
|
58
|
-
email: EmailStr
|
|
59
|
-
age: int = Field(ge=18, default=None)
|
|
60
|
-
```
|
|
61
|
-
|
|
62
|
-
### 3. Dependencies for Validation
|
|
63
|
-
|
|
64
|
-
```python
|
|
65
|
-
async def valid_post_id(post_id: UUID4) -> dict:
|
|
66
|
-
post = await service.get_by_id(post_id)
|
|
67
|
-
if not post:
|
|
68
|
-
raise PostNotFound()
|
|
69
|
-
return post
|
|
70
|
-
|
|
71
|
-
@router.get("/posts/{post_id}")
|
|
72
|
-
async def get_post(post: dict = Depends(valid_post_id)):
|
|
73
|
-
return post
|
|
74
|
-
```
|
|
75
|
-
|
|
76
|
-
## Detailed Guides
|
|
77
|
-
|
|
78
|
-
| Topic | File | When to Use |
|
|
79
|
-
|-------|------|-------------|
|
|
80
|
-
| Project Structure | [PROJECT-STRUCTURE.md](PROJECT-STRUCTURE.md) | Starting new project, organizing modules |
|
|
81
|
-
| Async Patterns | [ASYNC-PATTERNS.md](ASYNC-PATTERNS.md) | I/O operations, CPU tasks, blocking code |
|
|
82
|
-
| Pydantic Usage | [PYDANTIC-GUIDE.md](PYDANTIC-GUIDE.md) | Schema design, validation, config |
|
|
83
|
-
| Dependencies | [DEPENDENCIES.md](DEPENDENCIES.md) | Auth, validation, reusable logic |
|
|
84
|
-
| Database | [DATABASE.md](DATABASE.md) | SQLAlchemy, migrations, naming |
|
|
85
|
-
|
|
86
|
-
## Import Conventions
|
|
87
|
-
|
|
88
|
-
```python
|
|
89
|
-
# Cross-module imports - use explicit module names
|
|
90
|
-
from src.auth import constants as auth_constants
|
|
91
|
-
from src.notifications import service as notification_service
|
|
92
|
-
from src.posts.constants import ErrorCode as PostsErrorCode
|
|
93
|
-
```
|
|
94
|
-
|
|
95
|
-
## Testing Setup
|
|
96
|
-
|
|
97
|
-
```python
|
|
98
|
-
import pytest
|
|
99
|
-
from httpx import AsyncClient, ASGITransport
|
|
100
|
-
from src.main import app
|
|
101
|
-
|
|
102
|
-
@pytest.fixture
|
|
103
|
-
async def client():
|
|
104
|
-
async with AsyncClient(
|
|
105
|
-
transport=ASGITransport(app=app),
|
|
106
|
-
base_url="http://test"
|
|
107
|
-
) as client:
|
|
108
|
-
yield client
|
|
109
|
-
|
|
110
|
-
@pytest.mark.asyncio
|
|
111
|
-
async def test_endpoint(client: AsyncClient):
|
|
112
|
-
resp = await client.post("/posts")
|
|
113
|
-
assert resp.status_code == 201
|
|
114
|
-
```
|
|
115
|
-
|
|
116
|
-
## Code Quality
|
|
117
|
-
|
|
118
|
-
Use `ruff` for linting and formatting:
|
|
119
|
-
|
|
120
|
-
```bash
|
|
121
|
-
ruff check --fix src
|
|
122
|
-
ruff format src
|
|
123
|
-
```
|
|
1
|
+
---
|
|
2
|
+
name: fastapi-best-practices
|
|
3
|
+
description: FastAPI project structure, async patterns, Pydantic schemas, dependency injection, and database patterns. Use when building FastAPI backends, creating REST APIs, or reviewing Python web service code.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# FastAPI Best Practices
|
|
7
|
+
|
|
8
|
+
## Quick Start
|
|
9
|
+
|
|
10
|
+
```python
|
|
11
|
+
# Domain-based structure (recommended for scalable projects)
|
|
12
|
+
src/
|
|
13
|
+
├── auth/
|
|
14
|
+
│ ├── router.py # endpoints
|
|
15
|
+
│ ├── schemas.py # pydantic models
|
|
16
|
+
│ ├── models.py # db models
|
|
17
|
+
│ ├── service.py # business logic
|
|
18
|
+
│ ├── dependencies.py
|
|
19
|
+
│ └── exceptions.py
|
|
20
|
+
├── posts/
|
|
21
|
+
│ └── ...
|
|
22
|
+
├── config.py # global config
|
|
23
|
+
├── database.py # db connection
|
|
24
|
+
└── main.py # FastAPI app init
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
## Core Principles
|
|
28
|
+
|
|
29
|
+
### 1. Async Routes Done Right
|
|
30
|
+
|
|
31
|
+
```python
|
|
32
|
+
# BAD - blocks event loop
|
|
33
|
+
@router.get("/bad")
|
|
34
|
+
async def bad_route():
|
|
35
|
+
time.sleep(10) # blocks everything!
|
|
36
|
+
return {"ok": True}
|
|
37
|
+
|
|
38
|
+
# GOOD - sync route runs in threadpool
|
|
39
|
+
@router.get("/good")
|
|
40
|
+
def good_route():
|
|
41
|
+
time.sleep(10) # runs in separate thread
|
|
42
|
+
return {"ok": True}
|
|
43
|
+
|
|
44
|
+
# BEST - truly async
|
|
45
|
+
@router.get("/best")
|
|
46
|
+
async def best_route():
|
|
47
|
+
await asyncio.sleep(10) # non-blocking
|
|
48
|
+
return {"ok": True}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### 2. Pydantic Validation
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from pydantic import BaseModel, Field, EmailStr
|
|
55
|
+
|
|
56
|
+
class UserCreate(BaseModel):
|
|
57
|
+
username: str = Field(min_length=1, max_length=128, pattern="^[A-Za-z0-9-_]+$")
|
|
58
|
+
email: EmailStr
|
|
59
|
+
age: int = Field(ge=18, default=None)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### 3. Dependencies for Validation
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
async def valid_post_id(post_id: UUID4) -> dict:
|
|
66
|
+
post = await service.get_by_id(post_id)
|
|
67
|
+
if not post:
|
|
68
|
+
raise PostNotFound()
|
|
69
|
+
return post
|
|
70
|
+
|
|
71
|
+
@router.get("/posts/{post_id}")
|
|
72
|
+
async def get_post(post: dict = Depends(valid_post_id)):
|
|
73
|
+
return post
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Detailed Guides
|
|
77
|
+
|
|
78
|
+
| Topic | File | When to Use |
|
|
79
|
+
|-------|------|-------------|
|
|
80
|
+
| Project Structure | [PROJECT-STRUCTURE.md](PROJECT-STRUCTURE.md) | Starting new project, organizing modules |
|
|
81
|
+
| Async Patterns | [ASYNC-PATTERNS.md](ASYNC-PATTERNS.md) | I/O operations, CPU tasks, blocking code |
|
|
82
|
+
| Pydantic Usage | [PYDANTIC-GUIDE.md](PYDANTIC-GUIDE.md) | Schema design, validation, config |
|
|
83
|
+
| Dependencies | [DEPENDENCIES.md](DEPENDENCIES.md) | Auth, validation, reusable logic |
|
|
84
|
+
| Database | [DATABASE.md](DATABASE.md) | SQLAlchemy, migrations, naming |
|
|
85
|
+
|
|
86
|
+
## Import Conventions
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
# Cross-module imports - use explicit module names
|
|
90
|
+
from src.auth import constants as auth_constants
|
|
91
|
+
from src.notifications import service as notification_service
|
|
92
|
+
from src.posts.constants import ErrorCode as PostsErrorCode
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
## Testing Setup
|
|
96
|
+
|
|
97
|
+
```python
|
|
98
|
+
import pytest
|
|
99
|
+
from httpx import AsyncClient, ASGITransport
|
|
100
|
+
from src.main import app
|
|
101
|
+
|
|
102
|
+
@pytest.fixture
|
|
103
|
+
async def client():
|
|
104
|
+
async with AsyncClient(
|
|
105
|
+
transport=ASGITransport(app=app),
|
|
106
|
+
base_url="http://test"
|
|
107
|
+
) as client:
|
|
108
|
+
yield client
|
|
109
|
+
|
|
110
|
+
@pytest.mark.asyncio
|
|
111
|
+
async def test_endpoint(client: AsyncClient):
|
|
112
|
+
resp = await client.post("/posts")
|
|
113
|
+
assert resp.status_code == 201
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Code Quality
|
|
117
|
+
|
|
118
|
+
Use `ruff` for linting and formatting:
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
ruff check --fix src
|
|
122
|
+
ruff format src
|
|
123
|
+
```
|