개발하자

인증 시 FastApi 422 처리할 수 없는 엔티티, 수정하는 방법?

Cuire 2023. 8. 18. 12:16
반응형

인증 시 FastApi 422 처리할 수 없는 엔티티, 수정하는 방법?

내부 기능을 모두 삭제하고 인쇄해도 이해할 수 없지만 fastapi 문서를 사용하고 서명을 시도하면 작동합니다.

@auth_router.post('/signin')
async def sign_in(username: str = Form(...), password: str = Form(...)) -> dict:
    user = await authenticate_user(username, password)

    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED, 
            detail='Invalid username or password',
        )

    user_obj = await User_Pydantic.from_tortoise_orm(user)
    user_token = await generate_token(user_obj)

    return {
        'access_token': user_token,
        'token_type': 'bearer',
    }

OAuth2PasswordRequestForm을 사용하기 전에 422 오류가 발생하면 다른 방법을 시도하십시오.

내 모델은 거북이 또는 m이고, 필요할 때 그것을 pydantic 모델로 변환한다, 문서에서는 모든 것이 일이다.

JS

handleEvent(signinform, 'submit', e => {
    e.preventDefault();
    if(!isEmpty(signinform)){

        signInUsername = getElement('input[name="username"]', signinform).value;
        signInPassword = getElement('input[name="password"]', signinform).value;
        recaptchaV3 = getElement('[name="g-recaptcha-response"]').value;

        if(recaptchaV3){
            signInData = new FormData();
            signInData.append('username', signInUsername);
            signInData.append('password', signInPassword);

            isLogened = request('POST', '/signin', signInData);
            if(isLogened){
                log(isLogened);
            }
            
        } else{
            alert('Reload Page');
        }

    }

})

authenticate_사용자 func

async def authenticate_user(username: str, password: str):
    user = await User.get(username=username)

    if not user or not user.verify_password(password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED, 
            detail='Invalid username or password',
        )
    return user

내 요청 기능

const request = (method, url, data = null) => {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest()
        xhr.open(method, url, true)
        xhr.setRequestHeader('Content-Type', 'application/json')
        xhr.onerror = function () {
            console.log(xhr.response);
        };
        xhr.onload = () => {
        if (xhr.status === 200) {
            return resolve(JSON.parse(xhr.responseText || '{}'))
            } else {
                return reject(new Error(`Request failed with status ${xhr.status}`))
            }
        } 
        if (data) {
            xhr.send(JSON.stringify(data))
        } else {
            xhr.send()
        }


    })
}



오류를 게시하지 않았지만, 누가 문제를 알려주는 것이 목적입니다. 문제는 요청을 수행하는 방식에 있다고 확신합니다.

그 라인

xhr.setRequestHeader('Content-Type', 'application/json')

json 데이터를 보낸다는 뜻입니다. 이 데이터는 openapi 인증 형식에서 허용되지 않습니다. 또한 데이터를 json으로 문자열화하고 있습니다. json의 형식은 허용되지 않습니다.

따라서 내용 유형을 로 변경하고 요청 본문에 개체를 추가하면 작업이 가능합니다.

당신은 아래 깃허브 토론에서 그것을 볼 수 있다

https://github.com/tiangolo/fastapi/issues/2740 https://github.com/tiangolo/fastapi/issues/1431




요청에 내용 유형을 제공했는지 확인하십시오,

xhr.setRequestHeader('Content-Type', 'application/json')

입력된 내용이 있으면 입력 형식을 확인하십시오. 여기서 signInUsername과 signInPassword의 두 가지 변수를 선언했습니다.

중요: FastAPI에서 이러한 파일의 기본값을 제공할 수 있습니다. 이 경우 빈 내용이나 null을 속성 값으로 제공하면 fastapi에서 위와 같은 오류가 발생합니다.

서버로 보내는 데이터가 올바른지 확인합니다.




콘텐츠 유형을 다음으로 변경해 보십시오:

content_type: application/x-www-form-urlencoded

반응형