Skip to content

Commit

Permalink
Merge pull request #9 from f-lab-edu/feature/2
Browse files Browse the repository at this point in the history
[#8] 콘텐츠 검색 및 필터링 기능 구현 쿼리 최적화
  • Loading branch information
wktls63 authored Oct 1, 2024
2 parents 738b337 + e15fc9c commit 3379dff
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 23 deletions.
15 changes: 11 additions & 4 deletions services/content-service/app/content.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
# content.py

from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.orm import Session
from app.schemas import ContentCreate, Content as ContentSchema
Expand All @@ -22,10 +21,17 @@ def create_content(content: ContentCreate, db: Session = Depends(get_db)):
db.refresh(new_content)
return new_content

# 콘텐츠 목록 조회 엔드포인트
# 콘텐츠 목록 조회 엔드포인트 (필터링 기능 추가)
@router.get("/", response_model=list[ContentSchema])
def get_contents(db: Session = Depends(get_db)):
contents = db.query(Content).all()
def get_contents(title: str = None, category: str = None, db: Session = Depends(get_db)):
query = db.query(Content)

if title:
query = query.filter(Content.title.ilike(f"%{title}%"))
if category:
query = query.filter(Content.category == category)

contents = query.all()
return contents

# 콘텐츠 삭제 엔드포인트
Expand All @@ -36,3 +42,4 @@ def delete_content(content_id: int, db: Session = Depends(get_db)):
raise HTTPException(status_code=404, detail="Content not found")
db.delete(content)
db.commit()

14 changes: 9 additions & 5 deletions services/content-service/app/models.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
from sqlalchemy import Column, Integer, String, Text
# models.py
from sqlalchemy import Column, Integer, String, Text, Index
from app.db import Base

# 콘텐츠 정보를 저장할 데이터베이스 모델 정의
class Content(Base):
__tablename__ = "contents"

id = Column(Integer, primary_key=True, index=True)
title = Column(String(255), nullable=False) # 콘텐츠 제목
description = Column(Text, nullable=True) # 콘텐츠 설명
category = Column(String, nullable=True) # 선택적 필드로 변경
creator = Column(String, nullable=True) # 선택적 필드로 변경
title = Column(String(255), nullable=False, index=True) # 인덱스 추가
description = Column(Text, nullable=True)
category = Column(String, nullable=True, index=True) # 인덱스 추가
creator = Column(String, nullable=True, index=True) # 인덱스 추가

# 복합 인덱스 추가
Index('idx_title_category', Content.title, Content.category)
15 changes: 11 additions & 4 deletions services/content-service/app/schemas.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
# schemas.py

from pydantic import BaseModel
from typing import Optional

# 콘텐츠 생성 시 사용할 스키마
class ContentCreate(BaseModel):
title: str
description: str
category: str # 필수 필드로 설정
creator: str # 필수 필드로 설정
category: str # 필수 필드
creator: str # 필수 필드

# 콘텐츠 조회 및 반환 스키마
class Content(ContentCreate):
id: int

class Config:
from_attributes = True

# 검색 및 필터링 시 사용할 스키마
class ContentFilter(BaseModel):
title: Optional[str] = None
category: Optional[str] = None
creator: Optional[str] = None
26 changes: 16 additions & 10 deletions services/content-service/tests/test_content.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
# test_content.py
from fastapi.testclient import TestClient
from app.main import app # FastAPI 앱을 임포트

Expand All @@ -10,8 +11,8 @@ def test_create_content():
json={
"title": "Test Movie",
"description": "A great movie",
"category": "Movie", # 필수 필드 추가
"creator": "John Doe" # 필수 필드 추가
"category": "Movie",
"creator": "John Doe"
}
)
assert response.status_code == 201
Expand All @@ -20,24 +21,29 @@ def test_create_content():

def test_get_content():
# 콘텐츠 생성 후 상태 확인
response = client.post(
client.post(
"/contents/",
json={
"title": "Test Performance",
"description": "A live performance",
"category": "Performance", # 필수 필드 추가
"creator": "Jane Smith" # 필수 필드 추가
"category": "Performance",
"creator": "Jane Smith"
}
)
assert response.status_code == 201 # 상태 코드 확인

# 콘텐츠 목록 조회
response = client.get("/contents/")
# 제목 필터링 테스트
response = client.get("/contents/?title=Test")
assert response.status_code == 200
contents = response.json()
assert len(contents) > 0
assert any(content["title"] == "Test Performance" for content in contents)

# 카테고리 필터링 테스트
response = client.get("/contents/?category=Performance")
assert response.status_code == 200
contents = response.json()
assert any(content["category"] == "Performance" for content in contents)


def test_delete_content():
# 콘텐츠 생성
Expand All @@ -46,8 +52,8 @@ def test_delete_content():
json={
"title": "Test Art",
"description": "An amazing art",
"category": "Art", # 필수 필드 추가
"creator": "John Artist" # 필수 필드 추가
"category": "Art",
"creator": "John Artist"
}
)
content_id = response.json()["id"]
Expand Down

0 comments on commit 3379dff

Please sign in to comment.