본문 바로가기

FastAPI3

[FastAPI] 쿠키 설정 및 쿠키 삭제 FastAPI 프로젝트에서 회원가입 및 로그인을 하면 토큰을 발행하게 되어 있다. 로그인 시에 해당 토큰을 프론트에 리턴하기 전에 쿠키에 설정하고, 또한 로그아웃 시에 쿠키를 삭제하는 로직을 추가하려고 한다. 로그인 코드 및 set_cookie async def login( req: UserLoginReqDto, response: Response ): email = req.email password = req.password user = await get_user_by_email(email) if not user: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="User does not exist", ) hashed_passwo.. 2023. 5. 2.
[FastAPI] Request에서 user 정보 얻기 해당 내용은 Startlette 공식 페이지와 스택오버플로우를 참고했다. Reqeust에 유저 정보 담기 FastAPI에서 Dependency를 이용해 token에서 유저 정보를 가져오기 위해서는 Request를 사용할 수 있다. async def get_current_user(req: Request): try: token = req.headers.get("authorization") secret_key = token_settings.secret_key algorithms = token_settings.algorithm verified_token = jwt.decode(token, secret_key, algorithms=algorithms) except jwt.ExpiredSignatureError: .. 2023. 4. 23.
[FastAPI] Pydantic validator의 재사용 Validator pydantic의 BaseModel을 사용하여 프론트에서 받을 Body 값을 지정하는 동시에 Body 값 중에 validator가 필요한 경우 pydantic model 안에서 정의할 수 있다. 아래의 예시는 pydantic 공식 페이지에서 제공하는 예시와 설명이다. from pydantic import BaseModel, ValidationError, validator class UserModel(BaseModel): name: str username: str password1: str password2: str @validator('name') def name_must_contain_space(cls, v): if ' ' not in v: raise ValueError('must c.. 2023. 4. 21.