MongoDB Aggregate 파이프라인
·
DataBase/MongoDB
MongoDB의 aggregate 파이프라인은 데이터를 처리하고 분석하는 강력한 도구입니다. 데이터를 단계별로 처리하여 원하는 결과를 얻을 수 있습니다.기본 구조db.collection.aggregate([ { $match: { /* 조건 */ } }, { $group: { /* 그룹화 */ } }, { $sort: { /* 정렬 */ } }])$match: 데이터 필터링// 가격이 1000 이상인 상품 필터링db.products.aggregate([ { $match: { price: { $gte: 1000 }, category: "electronics" } }])$group: 데이터 그룹화// 카테고리별 평균 가..
FastAPI Security: API 보안 구현
·
파이썬/Fast API
# 기본 설치 (FastAPI에 포함되어 있음)pip install fastapi[all]pip install python-jose[cryptography] # JWT 토큰용pip install passlib[bcrypt] # 비밀번호 해싱용OAuth2 비밀번호 인증from fastapi import FastAPI, Depends, HTTPException, statusfrom fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestFormfrom jose import JWTError, jwtfrom passlib.context import CryptContext# 기본 설정oauth2_scheme = OAuth2PasswordBeare..
SlowAPI: FastAPI에서 Rate Limiting 구현
·
파이썬/Fast API
# 설치pip install slowapipip install redis # Redis 백엔드 사용시기본 Rate Limiting 설정from fastapi import FastAPIfrom slowapi import Limiter, _rate_limit_exceeded_handlerfrom slowapi.util import get_remote_addressfrom slowapi.errors import RateLimitExceededlimiter = Limiter(key_func=get_remote_address)app = FastAPI()app.state.limiter = limiterapp.add_exception_handler(RateLimitExceeded, _rate_limit_exceed..
FastAPI Permissions: 권한 관리 구현
·
파이썬/Fast API
# 설치pip install fastapi-permissions기본 권한 설정from fastapi_permissions import ( Allow, Deny, Everyone, Authenticated, configure_permissions, has_permission)class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True) email = Column(String, unique=True) role = Column(String) def __acl__(self): return [ (Allow, "admin", "read"), ..
FastAPI-Users with MongoDB: JWT 인증
·
파이썬/Fast API
# 설치pip install fastapi-users[beanie]pip install motor기본 설정과 모델 정의from typing import Optionalfrom beanie import Documentfrom fastapi_users.db import BeanieBaseUserfrom pydantic import EmailStrclass User(BeanieBaseUser, Document): email: EmailStr hashed_password: str is_active: bool = True is_superuser: bool = False is_verified: bool = False class Settings: name = "users"..
Zod: TypeScript 스키마 검증
·
TypeScript
# 설치npm install zod기본 사용법import { z } from "zod";// 기본 스키마 정의const userSchema = z.object({ name: z.string(), age: z.number().min(0), email: z.string().email(), website: z.string().url().optional()});// 타입 추론type User = z.infer;// 데이터 검증try { const user = userSchema.parse({ name: "John", age: 30, email: "john@example.com" });} catch (error) { console.error(error);}고급 스키마 정의const a..
React Hook Form: 폼 상태 관리
·
TypeScript
React Hook Form은 고성능의 유연한 폼 유효성 검사를 제공하는 라이브러리입니다. 불필요한 리렌더링을 최소화하고, 사용하기 쉬운 API를 제공합니다.기본 설치 및 사용법npm install react-hook-formimport { useForm } from 'react-hook-form';interface FormInputs { email: string; password: string;}function LoginForm() { const { register, handleSubmit, formState: { errors } } = useForm(); const onSubmit = (data: FormInputs) => { console.log(data); }; return ( ..
PM2로 Node.js 애플리케이션 관리하기
·
Linux
PM2는 Node.js 애플리케이션을 위한 강력한 프로덕션 프로세스 관리자입니다. 자동 실행, 로그 관리, 모니터링 등 다양한 기능을 제공합니다.PM2 설치 및 기본 명령어# 전역 설치npm install -g pm2# 기본 실행pm2 start app.js# 모든 프로세스 확인pm2 list# 특정 프로세스 중지pm2 stop app_name# 모든 프로세스 중지pm2 stop all프로세스 구성 설정// ecosystem.config.jsmodule.exports = { apps: [{ name: "api-server", script: "./src/index.js", instances: "max", exec_mode: "cluster", watch: true, env..