코딩캠프/AI 웹개발 취업캠프

[AI 웹개발 취업캠프] 23.08.16 과제

고랑E 2023. 8. 16. 23:59
728x90

오늘 api 수정사항 수정하여 다시 뼈대 잡기

지난(14일) 과제에서 강사님이 피드백 해주신 내용

 

  1. 전체: 응답에 단순히 메세지만 주는건 적절하지 않다 / 상태코드 부분까지
  2. 로그인: 쿠키 정보
  3. 로그아웃: 식별되야 로그아웃한다
  4. 회원가입: 리다이렉트
  5. 마이페이지(조회): 다른사람이 요청했을때
  6. 마이페이지(수정): 적어둔 요청데이터(사실 요청보낼 데이터들을 적어둔거긴 한대)에는 모든데이터를 patch로 따로 표기안해놔서 ㅎㅎ (모든 데이터 변경은 put)
  7. 닉네임,이메일 중복 체크 api 추가?
  8. 이메일 인증: 보내는 api, 인증코드 체크 api
  9. 단축주소: 해당 유저가 생성한 단축주소 api

express로 api 디자인 했던 방식대로 진행함

 

정리된 구글 시트

https://docs.google.com/spreadsheets/d/1zyd1Zxbp-21tK_1vjcWzZvE9f-f3Ce1CQ0v_6clSquQ/edit?usp=sharing 

 

NIPA myweb API 디자인

시트1 기능,메소드,URI,Request,Response,Response(error) 로그인,POST,/login,{ "loginId": "user1234", "password": "pw1234" },200 / 로그인 성공 { "message": "로그인 되었습니다.", "accessToken": "eyJhbGciO.......", "refreshToken": "eyJhbG

docs.google.com

 


디자인 한 REST API 뼈대 FastAPI 로 라우터 구현하기

로그인

api

더보기
# 로그인
@app.post("/login")
async def login(loginUser: LoginUser):
    mylogger.debug(loginUser)
    return loginUser

 

dto

더보기
class LoginUser(BaseModel):
    loginId: str
    password: str

 

로그아웃

api

 

https://fastapi.tiangolo.com/es/advanced/custom-response/#redirectresponse

 

Custom Response - HTML, Stream, File, others - FastAPI

FastAPI framework, high performance, easy to learn, fast to code, ready for production

fastapi.tiangolo.com

위 링크 참고하여 로그아웃시 리다이렉트 시킴

더보기

 

from fastapi.responses import RedirectResponse


# 로그아웃
@app.post("/logout")
async def logout():
    # Response.delete_cookie(key="access_token")
    return RedirectResponse("/", 200)

 

회원가입

api

더보기
@app.post("/join")
async def join(joinUser: User):
    mylogger.debug(joinUser)
    return joinUser

dto

더보기
class User(BaseModel):
    loginId: str
    nickname: str
    password: str
    email: str
    emailVerified: bool = False
    introduction: str = ""
    image: str = "/./images/baseprofile.png"
    loginMethod: str = "local"
    createdAt: Union[datetime, None] = datetime.today()
    updatedAt: Union[datetime, None] = datetime.today()

 

 

중복체크(아이디, 이메일, 닉네임)

api

더보기
# 아이디 중복체크
@app.get("/users/check/id")
async def check_id(id: checkId):
    mylogger.debug(id)
    return id

# 이메일 중복체크
@app.get("/users/check/email")
async def check_email(email: checkEmail):
    mylogger.debug(email)
    return email

# 닉네임 중복체크
@app.get("/users/check/nickname")
async def check_nickname(nickname: checkNickname):
    mylogger.debug(nickname)
    return nickname

 

dto

더보기
class checkId(BaseModel):
    id: str

class checkEmail(BaseModel):
    email: str

class checkNickname(BaseModel):
    nickname: str

 

마이페이지(조회, 수정)

api

더보기
# 마이페이지(조회)
@app.get("/users/info/{id}")
async def mypage(id):
    mylogger.debug(id)
    return id

# 마이페이지(수정)
@app.patch("/users/info/{id}")
async def mypage_edit(userUpdate: UserUpdate):
    userUpdate = {key: value for key, value in userUpdate.model_dump().items() if value is not None}
    mylogger.debug(userUpdate)
    return userUpdate

코드 중에

key: value for key, value in userUpdate.model_dump().items() if value is not None

 부분은

1. userUpdate 객체의 모든 키/값을 튜플로 변환하고

2. 키와 값을 돌면서 변수에 저장하고

3. 값이 None이 아닌 경우에만

4. 새로운 딕셔너리를 생성

 

그래서 None이 아닌 필드만 새로운 딕셔너리를 만들어서 반환하는 코드

 

전 과 후

 

dto

더보기
class UserUpdate(BaseModel):
    nickname: Union[str, None] = None
    password: Union[str, None] = None
    email: Union[str, None] = None
    introduction: Union[str, None] = None
    image: Union[str, None] = None
    updatedAt: Union[datetime, None] = datetime.today()

 

이메일(인증)

api

더보기
# 이메일 인증
@app.post("/users/email/{id}")
async def email_verified(emailVerified: checkEmail):
    mylogger.debug(emailVerified)
    return emailVerified

# 이메일 인증코드 확인
@app.post("/users/email-code-check/{id}")
async def email_code_check(emailCode: checkEmail):
    mylogger.debug(emailCode)
    return emailCode

 

단축주소(생성, 조회)

페이지

임시 샘플 데이터

더보기
_sample_shorts = [
    {"id": 1, "userId": 1, "originalUrl": "https://naver.com", "shortUrl": "https://url.kr/sturl1", "createdAt": date.today()},
    {"id": 2, "userId": 1, "originalUrl": "https://google.com", "shortUrl": "https://url.kr/sturl2", "createdAt": date.today()}
    ]

 

api

더보기
# 단축주소 페이지(조회)
@app.get("/shorts")
async def shorts():
    mylogger.debug(_sample_shorts)
    return _sample_shorts

 

생성

api

더보기
# 단축주소 생성
@app.post("/shorts")
async def shorts_add(shorts: Short):
    mylogger.debug(shorts)
    return shorts

 

조회(유저)

api

더보기
# 단축주소 유저 조회
@app.get("/shorts/users/{id}")
async def shorts_users(id: int):
    shorts = []
    for _user_sample_shorts in _sample_shorts:
        if _user_sample_shorts["userId"] == id:
            shorts.append(Short(**_user_sample_shorts))
    mylogger.debug(shorts)
    return shorts

 

조회(단일)

api

더보기
# 단축주소 단일 조회
@app.get("/shorts/list/{id}")
async def shorts_list(id: int):
    shorts = []
    for _user_sample_shorts in _sample_shorts:
        if _user_sample_shorts["id"] == id:
            shorts.append(Short(**_user_sample_shorts))
    mylogger.debug(shorts)
    return shorts

 

 

과제 제출 깃헙 주소 및 썬더클라이언트 파일

 

https://github.com/go-tiger/AI-web-camp/commit/5a743a227b5de7e0ed118bd354c2af3f3a299771

 

과제: 8.16 FastAPI 로 라우터 구현 · go-tiger/AI-web-camp@5a743a2

go-tiger committed Aug 16, 2023

github.com

 

thunder-collection_NIPA-myweb 8.16.json
0.01MB

 

본 후기는 정보통신산업진흥원(NIPA)에서 주관하는 <AI 서비스완성! AI+웹개발 취업캠프 - 프론트엔드&백엔드> 과정 학습/프로젝트/과제 기록으로 작성되었습니다.