1.Pydantic사용법
Pydantic
이라는 이름은 Python 기반의 타입 힌트 및 데이터 검증 라이브러리로서, “엄격하고 꼼꼼한 데이터 검증”이라는 컨셉을 “Pedantic”에서 가져와 “Py”와 결합시킨 합성어
Pydantic은 데이터 유효성 검증을 위해 주로 사용되며, 타입 힌트를 통해 안전하게 데이터를 핸들링합니다.
1.1 Pydantic 소개&기능
- DataValidation/SettingsManagement라이브러리
- TypeHint를 런타임에서 강제해 안전하게 데이터핸들링

- 머신러닝 FeatureDataValidation으로도 활용가능

pydantic은 validation 및 config 관리를 하는데 이 두가지 기능에 대해서 배워보자.
1.2 Validation
Machine LearningModel Input Validation
일반 Python class 활용


- PythonClass로InputDefinition및Validation=>의미없는코드가많아짐
- 복잡한 검증 로직엔 ClassMethod가 복잡해지기쉬움
- ExceptionHandling을 어떻게할지등 커스텀하게 제어할 수 있는 있지만 메인로직(Input을받아서Inference를수행하는)에집중하기어려워짐
DataClass 활용

- dataclass decorator 사용으로init_method를 작성필요x

- 인스턴스 생성시점에서 Validation을 수행하기쉬움
- 여전히 Validation로직들을 직접 작성해야함
- Validation 로직을 따로 작성하지 않으면,런타임에서 typechecking을 지원하지 않음
Pydantic활용


- 훨씬 간결해 진코드(6라인) (vs52라인PythonClass,vs 50라인dataclass)
- 주로 쓰이는 타입들(httpurl,dburl,enum등)에대한 Validation이 만들어져 있음
- 런타임에서 TypeHint에 따라서 ValidationError발생
- CustomType에 대한 Validation도 쉽게 사용가능

pydantic을 활용하면 위 이미지 처럼 어디서 에러가 발생했는지 알려준다.
1.3 Config
앱을 기동하기 위해,사용자가 설정해야 하는 일련의정보:Config
Config관리-1) 코드 내 상수로 관리
가장간단하지만,보안정보(Secret)들이 코드에 그대로 노출->이슈
-> 따라서 보안정보들을 다루지 않는 경우나, 테스트 환경같이 임시환경에서만 사용하기 적합.

Config관리-2) yaml등과 같은 파일로 관리


별도의 파일에서 관리후,실행할때 파일을 지정해서 Config클래스에 주입하는방법
- 배포환경별로 파일을생성(dev_config.yaml,prod_config.yaml)
- 보안정보가 여전히 파일에 노출되므로,배포환경별로 파일이 노출되지 않게 관리필요
Config관리-3) 환경변수(+Pydantic.BaseSettings)로관리
환경변수에 설정 값을 저장한뒤,코드에서는 환경변수를 읽어오는방법
- Validation처럼 Pydantic은 BaseSettings를상속한 클래스에서TypeHint로 주입된 설정 데이터를 검증할 수 있음
- Field 클래스의 env인자:환경변수를해당필드로 오버라이딩
- yaml,ini파일들을 추가적으로 만들지않고,.env파일들을 환경별로 만들어두거나,실행환경에서 유연하게 오버라이딩
- 보통 환경변수는 배포할때주입
- 코드나 파일에 보안정보가 노출되지 않음

특히 FastAPI를쓴다면 Pydantic.BaseSettings를통해 Config를 관리하는것을 추천
2.FastAPI 확장기능
2.1 Lifespan function
FastAPI앱을 실행할때와 종료할때,로직을 넣고 싶은경우

asyncdeflifespan(app:FastAPI)정의
- yield를 기점으로
- yield 이전라인은 앱시작전
- yield 이후라인은 앱종료전
FastAPI 인스턴스 생성시 lifespan 파라미터에 위 함수를 전달
- FastAPI(lifespan=lifespan)

2.2 API Router
API Router'는 API 엔드포인트를 모듈화하고 효율적으로 관리하는 데 사용됩니다. 이를 통해 코드의 구조를 개선하고 유지 보수를 용이하게 할 수 있습니다.
API엔드포인트가 점점많아져서, @app.get,@app.post
와 같은 코드를 하나의 모듈에서 관리하기가 어려워질 수 있음
APIRouter는 MiniFastAPI로 여러API를 연결해서 활용
- userRouter,orderRouter2개생성
- app에연결(include_router)
- 실제활용한다면 하나의 파일에 저장하지 않고 각각 저장
(user.py,order.py
)

2.3 Project structure


2.4 Error Handler
ErrorHandling
은 웹서버를 안정적으로 운영하기 위해 반드시 필요한 주제
- 서버에서 Error가 발생한경우,어떤Error가 발생했는지 알아야하고 요청한 클라이언트에 해당정보를 전달해 대응할 수 있어야함
- 서버개발자는 모니터링도구를 사용해 ErrorLog를 수집해야함
- 발생하고 있는 오류를 빠르게 수정할수있도록 예외처리를 잘 만들 필요가 있음
HTTPException
클래스는 FastAPI에서 오류 처리를 위해 사용됩니다. 이를 통해 클라이언트에게 보다 상세한 에러 메시지를 제공할 수 있습니다.
에러핸들링 없는 경우

- item_id가5일경우
InternalServerError500Return
- 이렇게되면 클라이언트는 어떤 에러가 난 것인지 정보를 얻을수 없고,자세한 에러를 보려면 서버에 직접 접근해서 로그를 확인
- 에러핸들링을 더 잘하려면 에러메시지와 에러의이유 등을 클라이언트에 전달하도록 코드를 작성
에러핸들링 있는 경우

2.5 Background Tasks
FastAPI의 기능중 BackgroundTasks 기능은 오래걸리는 작업들을 background에서 실행함-> 클라이언트에게 비동기로 처리하도록 하고 싶은 경우인 것임.
Background 사용하지 않는 작업 예시

Background 사용하는 작업 예시
Background 사용한 태스크는 바로 실행

작업 결과물을 조회할때는 Task를 어딘가에 저장해두고,GET요청을통해 Task가 완료됐는지확인

3.FastAPI가 어렵다면
3.1 FastAPI가 어려운이유
프로젝트 구조 어떻게 잡아야하지?, 백엔드 프로그래밍이 처음
3.2 프로젝트구조-Cookiecutter
쿠키를 만들때 사용하는 Cookiecutter -> 많은 사람들이 프로젝트 구조에 대해서 고민하여 템플렛 공유.
https://github.com/cookiecutter/cookiecutter
Cookiecutter Data Science
https://github.com/drivendataorg/cookiecutter-data-science

cookitcutter-fastapi
https://github.com/arthurhenrique/cookiecutter-fastapi

3.3 객체지향
- 객체지향프로그래밍은 코드의 중복을 최소화해서 재사용성을 증가시킴
- 복잡한 로직이 들어갈수록 점점 빛을 발휘함
3.4 Try&Error
목표를설정하고(무엇을만들겠다)=>기능을정의=>하나씩구현
- 막연히FastAPI를학습해야지보다는, 프로젝트를FastAPI백엔드로구현!등으로 목표설정