Add comprehensive skills and documentation for various technologies

This commit is contained in:
duthaho
2025-11-29 18:07:28 +07:00
commit ef96f165ef
60 changed files with 10538 additions and 0 deletions
+91
View File
@@ -0,0 +1,91 @@
# Django
## Description
Django web framework with ORM, views, and REST framework patterns.
## When to Use
- Python web applications
- Admin interfaces
- Django REST Framework APIs
---
## Core Patterns
### Models
```python
from django.db import models
class User(models.Model):
email = models.EmailField(unique=True)
name = models.CharField(max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return self.email
```
### Views (Class-based)
```python
from django.views.generic import ListView, DetailView
class UserListView(ListView):
model = User
template_name = 'users/list.html'
context_object_name = 'users'
paginate_by = 20
class UserDetailView(DetailView):
model = User
template_name = 'users/detail.html'
```
### Django REST Framework
```python
from rest_framework import serializers, viewsets
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'email', 'name', 'created_at']
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
```
### URLs
```python
from django.urls import path, include
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('users', UserViewSet)
urlpatterns = [
path('api/', include(router.urls)),
]
```
## Best Practices
1. Use class-based views for standard CRUD
2. Define model methods for business logic
3. Use serializers for validation
4. Add proper permissions
5. Use select_related/prefetch_related for queries
## Common Pitfalls
- **N+1 queries**: Use select_related/prefetch_related
- **Missing migrations**: Run makemigrations
- **No validation**: Use serializers properly
@@ -0,0 +1,89 @@
# FastAPI
## Description
FastAPI web framework with async patterns, Pydantic validation, and OpenAPI documentation.
## When to Use
- Building REST APIs with Python
- Async web applications
- OpenAPI/Swagger documentation needed
---
## Core Patterns
### Route Definition
```python
from fastapi import FastAPI, HTTPException, Depends
from pydantic import BaseModel
app = FastAPI()
class UserCreate(BaseModel):
email: str
name: str
class UserResponse(BaseModel):
id: int
email: str
name: str
@app.post("/users", response_model=UserResponse, status_code=201)
async def create_user(user: UserCreate):
# Create user logic
return UserResponse(id=1, **user.model_dump())
@app.get("/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int):
user = await get_user_by_id(user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
```
### Dependency Injection
```python
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with async_session_maker() as session:
yield session
@app.get("/users")
async def list_users(db: AsyncSession = Depends(get_db)):
return await db.execute(select(User))
```
### Router Organization
```python
from fastapi import APIRouter
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/")
async def list_users():
pass
# In main.py
app.include_router(router)
```
## Best Practices
1. Use Pydantic models for request/response validation
2. Organize routes with APIRouter
3. Use dependency injection for services
4. Return proper HTTP status codes
5. Add OpenAPI descriptions
## Common Pitfalls
- **Blocking I/O in async**: Use async libraries
- **Missing response models**: Always define them
- **No error handling**: Use HTTPException properly
+112
View File
@@ -0,0 +1,112 @@
# Next.js
## Description
Next.js framework with App Router, Server Components, and full-stack development patterns.
## When to Use
- React applications with SSR/SSG
- Full-stack applications
- App Router patterns
---
## Core Patterns
### App Router Structure
```
app/
├── layout.tsx # Root layout
├── page.tsx # Home page
├── loading.tsx # Loading UI
├── error.tsx # Error UI
├── api/
│ └── users/
│ └── route.ts # API route
└── users/
├── page.tsx # Users page
└── [id]/
└── page.tsx # User detail
```
### Server Components
```tsx
// app/users/page.tsx - Server Component (default)
async function UsersPage() {
const users = await db.users.findMany();
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
```
### Client Components
```tsx
'use client';
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>
);
}
```
### API Routes
```typescript
// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
export async function GET() {
const users = await db.users.findMany();
return NextResponse.json(users);
}
export async function POST(request: NextRequest) {
const data = await request.json();
const user = await db.users.create({ data });
return NextResponse.json(user, { status: 201 });
}
```
### Server Actions
```tsx
// app/actions.ts
'use server';
export async function createUser(formData: FormData) {
const name = formData.get('name') as string;
await db.users.create({ data: { name } });
revalidatePath('/users');
}
```
## Best Practices
1. Use Server Components by default
2. Add 'use client' only when needed
3. Colocate data fetching with components
4. Use loading.tsx for suspense boundaries
5. Implement proper error boundaries
## Common Pitfalls
- **Using hooks in Server Components**: Mark as 'use client'
- **Large client bundles**: Keep client components small
- **Missing loading states**: Add loading.tsx files
+108
View File
@@ -0,0 +1,108 @@
# React
## Description
React component patterns, hooks, and state management best practices.
## When to Use
- Building React components
- Using React hooks
- Component state management
---
## Core Patterns
### Functional Components
```tsx
interface UserCardProps {
user: User;
onSelect?: (user: User) => void;
}
export function UserCard({ user, onSelect }: UserCardProps) {
return (
<div className="card" onClick={() => onSelect?.(user)}>
<h3>{user.name}</h3>
<p>{user.email}</p>
</div>
);
}
```
### Hooks
```tsx
// useState
const [count, setCount] = useState(0);
// useEffect
useEffect(() => {
const subscription = subscribe();
return () => subscription.unsubscribe();
}, [dependency]);
// useMemo
const expensive = useMemo(() => compute(data), [data]);
// useCallback
const handleClick = useCallback(() => {
doSomething(id);
}, [id]);
```
### Custom Hooks
```tsx
function useUser(id: string) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true);
fetchUser(id)
.then(setUser)
.finally(() => setLoading(false));
}, [id]);
return { user, loading };
}
```
### Context Pattern
```tsx
const UserContext = createContext<User | null>(null);
export function UserProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
return (
<UserContext.Provider value={user}>
{children}
</UserContext.Provider>
);
}
export function useUser() {
const context = useContext(UserContext);
if (!context) throw new Error('useUser must be within UserProvider');
return context;
}
```
## Best Practices
1. Keep components small and focused
2. Use TypeScript for props
3. Memoize expensive computations
4. Clean up effects properly
5. Lift state up when needed
## Common Pitfalls
- **Missing dependencies in hooks**: Include all dependencies
- **State updates on unmounted**: Use cleanup functions
- **Prop drilling**: Use context or composition