Web/슈퍼코딩

(2024.12.09(월요일)) 슈퍼코딩 (신입연수원) 3주차 Day 1 후기

유니얼 2024. 12. 9. 17:29
728x90

MongoDB와 Python을 활용한 친구 목록 관리

1, MongoDB란?

MongoDB는 NoSQL 데이터베이스로, 데이터를 JSON과 유사한 BSON(Binary JSON) 형식으로 저장합니다. 관계형 데이터베이스와달리 스키마가 고정되지 않아 구조가 유연하며, 대규모 데이터 처리와 확장성에서 강점을 가집니다. 특히, 문서(Document) 단위로 데이터를 관리하며, 컬렉션(Collection) 안에 여러 문서를 저장하는 방식으로 구성됩니다.

주요 특징:

  • NoSQL: 비관계형 데이터베이스로, 정형화된 테이블이 아닌 문서 기반 데이터 저장 방식.
  • 유연한 스키마: 구조를 변경할 때 전체 데이터베이스를 변경하지 않아도 됨.
  • 확장성: 샤딩과 복제 기능을 통해 대규모 데이터를 효과적으로 처리.
  • 다양한 언어 지원: Python, JavaScript, Java 등 다양한 프로그래밍 언어와의 연동 지원.

2. Python으로 MongoDB 연동 및 친구 목록 데이터 관리

Python에서 MongoDB를 연동하기 위해 pymongo 라이브러리를 사용했습니다. 이 프로젝트에서는 FastAPI를 기반으로 REST API를 구현하여 MongoDB의 CRUD(Create, Read, Update, Delete) 작업을 처리했습니다.

코드 주요 기능:

  • 데이터 생성: 새로운 친구 데이터를 추가.
  • 데이터 조회: 저장된 모든 친구 데이터를 확인.
  • 데이터 삭제: 특정 친구 데이터를 삭제.
  • 데이터 수정: 기존 데이터를 업데이트.

1. MongoDB와 연결:

from pymongo import MongoClient

# MongoDB 연결
client = MongoClient("mongodb://localhost:27017")
# 데이터베이스 선택 (존재하지 않을 경우 새로 생성)
db = client["friends_db"]
# 컬렉션 선택 (여기서는 'memos'라는 컬렉션을 사용)
collection = db["friends"]

2. 친구 추가 API:

@app.post('/friends')
def create_friend(name:Annotated[str,Form()],
                  phone:Annotated[int,Form()]):
    # 입력받은 이름과 전화번호로 데이터 형식을 만든다.
    friend = {
        "name": name,
        "phone": phone
    }
    # 만들고 데이터를 추가한다.
    result = collection.insert_one(friend)
    print(f"Inserted memo with id {result.inserted_id}")
    return f"Inserted memo with id {result.inserted_id}"

3. 모든 친구 조회 API:

@app.get('/friends')
def get_friends():
    # 모든 데이터를 가져온다.
    rows = collection.find()
    # 가져온 데이터를 전부 Json 형식으로 변환한다.
    friends = [
        {**row, "_id": str(row["_id"])} for row in rows
    ]
    print(friends)
    return JSONResponse(jsonable_encoder(friends))

4, Name으로 친구 조회 API:

@app.post('/find/name={name}')
def find_friends(name):
    # name이 일치하는 데이터를 찾는다.
    result = collection.find_one({"name": name})
    # 데이터가 없으면 404 에러를 반환
    if not result:
        raise HTTPException(
            status_code=404,
            detail=f"Friend with name '{name}' not found."
        )

    # ObjectId를 문자열로 변환
    result["_id"] = str(result["_id"])
    return JSONResponse(content=jsonable_encoder(result))

5. 친구 수정 API:

@app.post('/update/id={friend_id}')
def update_friend(friend_id,
                  name:Annotated[str,Form()],
                  phone:Annotated[int,Form()]):
    # friend_id가 적합한 ID 값인디 확인
    if not ObjectId.is_valid(friend_id):
        raise HTTPException(
            status_code=400,
            detail="Invalid friend_id format"
        )

    # 업데이트 실행
    result = collection.update_one(
        {"_id": ObjectId(friend_id)},
        {"$set": {"name": name, "phone": phone}}
    )

    # 해당 ID를 기준으로 matched_count가 없으면 ID에 해당하는 데이터가 없음으로 404 에러를 반환
    if result.matched_count == 0:
        raise HTTPException(
            status_code=404,
            detail=f"Friend with id '{friend_id}' not found."
        )

    print(f"Updated memo with id {friend_id}")
    return {"message": f"Updated memo with id {friend_id}"}

6. 친구 삭제 API:

@app.post('/delete/id={friend_id}')
def delete_friends(friend_id):
    # friend_id로 입력받은 데이터를 삭제한다.
    collection.delete_one({"_id": ObjectId(friend_id)})
    print(f"Deleted memo with id {friend_id}")
    return f"Deleted memo with id {friend_id}"

3. 일일 보고 양식

부족한 점: - Mongo DB, SQLite 등 데이터베이스 구조 설계 및 API 보안 강화를 위한 더 많은 학습 필요.

스스로 시도해본 것들 : 데이터베이스 구조 설계등에 대한 조사

알게된 점 : MongoDB ObjectId의 변환과 데이터 직렬화(JSON 처리)의 중요성.

회고 : 프로젝트를 통해 데이터베이스 설계와 RESTful API 개발에 대한 실무 감각을 얻음.

반응형