[fastapi] redirection 문제

HyunDong Lee·2022년 4월 28일
0

fastapi

목록 보기
1/1
post-thumbnail

html/window.location.href

버튼은 아래와 같은 모양으로 처음 구성했고 go live를 통하여 html 화면이 해당 버튼 클릭 시 전환되는 것을 확인.

<button type="button" onclick="window.location.href='signup.html'">
  SIGN UP
</button>

하지만 fastapi내에 templates를 사용하기 때문에 window location href가 local host이고 localhost에서 바로 login.html을 찾는다.

1.app.mount를 사용하여 templates 폴더를 찾게 구성

jinja2templates를 사용하여 화면을 전환시켜줄 함수를 찾았지만 해결이 되지 않았다.

2. back 쪽에서 화면을 전화시키는것은 좋은 방법이 아닌것 같음

로그인 경로로 되어있기 때문에 html 사이에서 화면이 전환되게 하는 것이 맞다.

"""login"""
@app.get('/login', response_class=HTMLResponse)
async def login(request:Request):
    return templates.TemplateResponse("login.html", {"request":request})


@app.post('/login')
def login(response:Response, data:OAuth2PasswordRequestForm = Depends(OAuth2PasswordRequestForm)):
    username = data.username
    password = data.password
    user = load_user(username, fake_db)
    # resp = Response.set_cookie(key="")
    if not user:
        raise InvalidCredentialsException
    elif not verify_password(password, user.hashed_password):
        raise InvalidCredentialsException

    """create access token"""
    access_token = managers.create_access_token(
        data=dict(sub=username), expires=timedelta(hours=12)
    )
    print(access_token)
    """set cookie"""
    managers.set_cookie(response, access_token)
    return RedirectResponse(url='/index', status_code=302)

3. window.location.replace

<button type="button" onclick="window.location.replace('/signup')">SIGN UP</button>

javascript window.location함수를 확인하면 쉽게 해결되는 문제였다!
출처

0개의 댓글