FastAPI
FastAPI로 이벤트 플래너 만들기 02 - 모델 구현 -
코딩하고분석하는돌스
2024. 5. 12. 11:23
FastAPI로 이벤트 플래너 만들기 02
- 모델 구현 -
이벤트 플래너를 만들기 위해 이벤트 모델과 사용자 모델을 구현한다.
1. events 모델 구현
models 디렉토리 안에 있는 events.py 파일에 아래의 내용을 구현한다.
# models/events.py
from pydantic import BaseModel
from typing import List
class Event(BaseModel):
id : int
title : str
image : str
description : str
tags : List[str]
location : str
# 위 모델의 샘플 데이터를 보여주기 위한 Config class 작성
class Config:
json_schema_extra = {
"example" : {
"title" : "이벤트 플래너 샘플",
"imgae" : "https://linktomyimage.com/image.png",
"description" : "이벤트 플래너 데이터 샘플",
"tags" : ["python","fastapi","book","sample"],
"location" : "서울"
}
}
2. 사용자 모델 구현
models 디렉토리의 users.py에 사용자 모델과 사용자 로그인 모델을 구현한다.
1) User 모델 구현
# model/users.py
from pydantic import BaseModel, EmailStr
from typing import Optional, List
from models.events import Event
# 사용자 모델
class User(BaseModel):
email : EmailStr
password : str
events : Optional[List[Event]]
# 입력 예제 작성
class Config:
json_schema_extra= {
"example" : {
"email" : "fastapi@naver.com",
"password" : "str0ng!!!!",
"events" : [],
}
}
2) UserSignIn 모델 (사용자 로그인 모델) 구현
User(사용자 모델) 바로 아래에 연달아서 작성한다.
# 사용자 로그인 모델
class UserSignIn(BaseModel):
email : EmailStr
password : str
class Config:
json_schema_extra = {
"example" : {
"email" : "fastapi@naver.com",
"password" : "string!!!",
"events" : [],
}
}
출처: 아데시나, 압둘라지즈 압둘라지즈. FastAPI를 사용한 파이썬 웹 개발. 번역 김완섭. 한빛미디어, 2023