전체 글
FastAPI Security: 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 구현
# 설치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: 권한 관리 구현
# 설치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 인증
# 설치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 스키마 검증
# 설치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: 폼 상태 관리
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 애플리케이션 관리하기
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..
Node-Cache : 서버 성능 최적화
Node-Cache는 Node.js 애플리케이션에서 메모리 캐싱을 구현할 수 있게 해주는 간단하고 강력한 모듈입니다. 데이터베이스 쿼리 결과나 API 응답을 캐싱하여 애플리케이션의 성능을 향상시킬 수 있습니다.기본 설치 및 설정const NodeCache = require('node-cache');// 기본 캐시 인스턴스 생성const cache = new NodeCache({ stdTTL: 600, // 기본 TTL 10분 checkperiod: 120 // 만료된 항목 점검 주기 2분});기본적인 캐시 사용법// 데이터 저장cache.set('user:123', { name: 'John', age: 30 });// 데이터 조회const data = cache.get('user:123');/..