Melon-Shake / API

2 stars 1 forks source link

[ Fast API ] 정호연이 에러를 빨리 확인 하는법 #46

Closed Lucete28 closed 1 year ago

Lucete28 commented 1 year ago

개요

상세 내용

(1단계) 기본적으로 fastapi에서 처리

아래 코드에서 보이는것처럼 HTTPException을 통해 Fast api 자체의 오류인지 확인합니다.

from fastapi import FastAPI,HTTPException

@app.post("/lyric_input/")
def lyric_input(item : lyric_data):
    artist = item.artist
    result = lyric_search_and_input(artist)

    if result:
        return {"result" : f"Lyrics have been added to track_id : {track_id}"}
    else:
        raise HTTPException(status_code=404, detail="Lyric ERR.")

(2단계) result 딕셔너리 리턴 활용

  1. 코드(함수) 가 시작할때 빈 result 딕셔너리를 선언
  2. if 문, try/exept문 for문 등 작업이 이루어 질 때마다 딕셔너리에 result['작업']=결과 형식으로 계속 추가
  3. 마지막에 result를 return시켜줍니다.
    def tmp( ):
    result = { }
    if True:
        something_result = do_something()
        result['do_something'] = something_result 
    else:
        nothing_result = do_nothing()
        result['do_nothing'] = nothing_result
    return result
jungssg commented 1 year ago

LGTM

dMario24 commented 1 year ago

복학 축하드립니다. 멀지 않은 훗날 개발자로 다시 만납시다 !!!

LGTM