Develop/FastAPI
FastAPI Path Parameters(열거형) - 06
김잠봉
2022. 12. 21. 14:19
728x90
1. Enum 모듈을 삽입
- 사전에 정해진 범위에 값이 있을 때 사용
- from enum import Enum
2. 새로운 클래스를 생성
- Enums 상속
- str 상속 -> 내부 클래스 변수들은 string 형식이라고 명
class DirectionName(str, Enum):
north = "North"
south = "South"
east = "East"
west = "West"
3. Path Parameters(경로 매개변수)
- url에서 값을 받음
@app.get("/directions/{direction_name}")
async def get_direction(direction_name: DirectionName):
if direction_name == DirectionName.north:
return {"Direction":direction_name, "sub":"Up"}
if direction_name == DirectionName.south:
return {"Direction":direction_name, "sub":"Down"}
if direction_name == DirectionName.west:
return {"Direction":direction_name, "sub":"Left"}
return {"Direction":direction_name, "sub":"Right"}
- 함수의 매개변수 direction_name의 범위를 DirectionName 인스턴스로 정의
- url로 받을 수 있는 값은 사전에 정의 DirectionName의 값만 가능

- 사전에 정의 된 값 이외에 값이 들어갔을 때

728x90
SMALL