Skip to content

Commit

Permalink
add: 영화 삽입하기 기능
Browse files Browse the repository at this point in the history
  • Loading branch information
korjsh committed Nov 20, 2024
1 parent 3cee44b commit 017664b
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 2 deletions.
37 changes: 37 additions & 0 deletions app/crud/movie.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,42 @@
from sqlalchemy.orm import Session
from app.models.movie import Movie
from typing import List
import pandas as pd

def search_movies_by_name(db: Session, keyword: str):
return db.query(Movie).filter(Movie.movie_nm.like(f"%{keyword}%")).all()

def create_movies_from_csv(db: Session, df: pd.DataFrame):
movies_to_add = []
for index, row in df.iterrows():
# 결측치 처리
row = row.fillna('')

# MovieInfo 객체 생성
movie = Movie(
no=int(row['NO']),
movie_nm=row['MOVIE_NM'],
drctr_nm=row['DRCTR_NM'] if row['DRCTR_NM'] else None,
makr_nm=row['MAKR_NM'] if row['MAKR_NM'] else None,
incme_cmpny_nm=row['INCME_CMPNY_NM'] if row['INCME_CMPNY_NM'] else None,
distb_cmpny_nm=row['DISTB_CMPNY_NM'] if row['DISTB_CMPNY_NM'] else None,
opn_de=row['OPN_DE'] if row['OPN_DE'] else None,
movie_ty_nm=row['MOVIE_TY_NM'] if row['MOVIE_TY_NM'] else None,
movie_stle_nm=row['MOVIE_STLE_NM'] if row['MOVIE_STLE_NM'] else None,
nlty_nm=row['NLTY_NM'] if row['NLTY_NM'] else None,
tot_scrn_co=float(row['TOT_SCRN_CO']) if row['TOT_SCRN_CO'] else None,
sales_price=float(row['SALES_PRICE']) if row['SALES_PRICE'] else None,
viewng_nmpr_co=float(row['VIEWNG_NMPR_CO']) if row['VIEWNG_NMPR_CO'] else None,
seoul_sales_price=float(row['SEOUL_SALES_PRICE']) if row['SEOUL_SALES_PRICE'] else None,
seoul_viewng_nmpr_co=float(row['SEOUL_VIEWNG_NMPR_CO']) if row['SEOUL_VIEWNG_NMPR_CO'] else None,
genre_nm=row['GENRE_NM'] if row['GENRE_NM'] else None,
grad_nm=row['GRAD_NM'] if row['GRAD_NM'] else None,
movie_sdiv_nm=row['MOVIE_SDIV_NM'] if row['MOVIE_SDIV_NM'] else None,
)
movies_to_add.append(movie)

# 데이터베이스에 추가
db.bulk_save_objects(movies_to_add)
db.commit()

return len(movies_to_add)
31 changes: 29 additions & 2 deletions app/routers/movie.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from sqlalchemy.orm import Session
from app.crud.movie import search_movies_by_name
from app.crud.movie import search_movies_by_name, create_movies_from_csv
from app.database import get_db
from app.schemas.movie import MovieInfoSchema
import pandas as pd
import io


from typing import List

Expand All @@ -18,3 +21,27 @@ def search_movie(title: str, db: Session = Depends(get_db)):

return searched_movies

@router.post("/upload-movies/")
async def upload_movies(file: UploadFile = File(...), db: Session = Depends(get_db)):
# 파일 형식 확인
if file.content_type != 'text/csv':
raise HTTPException(status_code=400, detail="CSV 파일만 업로드할 수 있습니다.")

try:
# 업로드된 파일 읽기
contents = await file.read()
# 판다스 데이터프레임으로 변환
df = pd.read_csv(io.StringIO(contents.decode('utf-8')))
except Exception as e:
raise HTTPException(status_code=400, detail="CSV 파일을 읽는 중 오류가 발생했습니다.")

try:
# 데이터베이스에 저장
num_movies = create_movies_from_csv(db, df)
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail="데이터베이스에 저장하는 중 오류가 발생했습니다.")

return {"message": f"{num_movies}개의 영화가 성공적으로 업로드되었습니다."}


0 comments on commit 017664b

Please sign in to comment.