-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path.cursorrules
More file actions
233 lines (206 loc) · 6 KB
/
.cursorrules
File metadata and controls
233 lines (206 loc) · 6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
// FastAPI Modern API Development Guide
// Author: {{AUTHOR_NAME}} ({{GITHUB_USERNAME}})
// What you can build with this ruleset:
A modern FastAPI application with:
- High-performance REST APIs
- Real-time WebSocket endpoints
- Async database operations
- OpenAPI documentation
- Type-safe request/response handling
- Authentication and authorization
- Background tasks
- Middleware integrations
// Project Structure
src/
main.py # Application entry point
core/ # Core functionality
config.py # Configuration
security.py # Security utilities
logging.py # Logging setup
api/ # API endpoints
v1/ # API version 1
routes/ # Route modules
models/ # Pydantic models
deps.py # Dependencies
db/ # Database
models.py # SQLAlchemy models
session.py # DB session
migrations/ # Alembic migrations
services/ # Business logic
schemas/ # Pydantic schemas
utils/ # Utilities
tests/ # Test suites
api/ # API tests
services/ # Service tests
// Development Guidelines
1. API Design:
- Use functional programming
- Implement proper validation
- Handle errors gracefully
- Use proper typing
- Implement proper documentation
- Follow REST principles
2. Performance Patterns:
- Use async operations
- Implement caching
- Optimize database queries
- Use connection pooling
- Handle background tasks
- Monitor performance
3. Code Organization:
- Separate concerns properly
- Use dependency injection
- Implement proper logging
- Handle configuration
- Use proper middleware
- Follow clean architecture
// Dependencies
Core:
- fastapi: "^0.104.0"
- pydantic: "^2.4.0"
- sqlalchemy: "^2.0.0"
- alembic: "^1.12.0"
- uvicorn: "^0.24.0"
- python-jose: "^3.3.0"
Optional:
- redis: "^5.0.0"
- celery: "^5.3.0"
- pytest: "^7.4.0"
- httpx: "^0.25.0"
// Code Examples:
1. Route Definition Pattern:
```python
from fastapi import APIRouter, Depends, HTTPException
from typing import List
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from ..deps import get_db
from ..models import UserRead, UserCreate
from ...services.user import UserService
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/", response_model=List[UserRead])
async def get_users(
skip: int = 0,
limit: int = 100,
db: AsyncSession = Depends(get_db)
) -> List[UserRead]:
"""
Retrieve users with pagination.
"""
try:
users = await UserService(db).get_users(skip=skip, limit=limit)
return users
except Exception as e:
raise HTTPException(
status_code=500,
detail="Failed to retrieve users"
)
@router.post("/", response_model=UserRead)
async def create_user(
user: UserCreate,
db: AsyncSession = Depends(get_db)
) -> UserRead:
"""
Create a new user.
"""
try:
return await UserService(db).create_user(user)
except ValueError as e:
raise HTTPException(
status_code=400,
detail=str(e)
)
```
2. Service Pattern:
```python
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from typing import List, Optional
from ..models import User
from ..schemas import UserCreate, UserUpdate
class UserService:
def __init__(self, db: AsyncSession):
self.db = db
async def get_users(
self,
skip: int = 0,
limit: int = 100
) -> List[User]:
query = select(User).offset(skip).limit(limit)
result = await self.db.execute(query)
return result.scalars().all()
async def get_user_by_id(self, user_id: int) -> Optional[User]:
query = select(User).where(User.id == user_id)
result = await self.db.execute(query)
return result.scalar_one_or_none()
async def create_user(self, user: UserCreate) -> User:
db_user = User(**user.model_dump())
self.db.add(db_user)
await self.db.commit()
await self.db.refresh(db_user)
return db_user
```
3. Dependency Pattern:
```python
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from sqlalchemy.ext.asyncio import AsyncSession
from ..core.config import settings
from ..db.session import async_session
from ..models import User
from ..services.user import UserService
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def get_db() -> AsyncSession:
async with async_session() as session:
try:
yield session
finally:
await session.close()
async def get_current_user(
token: str = Depends(oauth2_scheme),
db: AsyncSession = Depends(get_db)
) -> User:
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(
token,
settings.SECRET_KEY,
algorithms=[settings.ALGORITHM]
)
user_id: int = payload.get("sub")
if user_id is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = await UserService(db).get_user_by_id(user_id)
if user is None:
raise credentials_exception
return user
```
// Best Practices:
1. Use type hints consistently
2. Implement proper validation
3. Handle errors gracefully
4. Use async operations
5. Implement proper logging
6. Use dependency injection
7. Follow REST principles
8. Implement proper testing
9. Use proper documentation
10. Monitor performance
// Security Considerations:
1. Validate input data
2. Use proper authentication
3. Implement rate limiting
4. Use secure headers
5. Handle sensitive data
6. Implement proper logging
7. Use proper encryption
8. Handle errors securely
9. Implement CORS properly
10. Follow security updates