Flutter & Python (fastapi) Login Function: 422 Unprocessable Entity

59 views Asked by At

Python code

  1. Model
  2. Login fast api (python)
from pydantic import BaseModel

class User(BaseModel):
    user_name: str
    real_name: str
    password: str
    phone_number: str
    email: str
    car_number: int
    car_color: str
    car_type: str
    # car_license: str
    homeroom: str
    user_type: str
    warning: list[str]
    penalty: int 
    
class User_login(BaseModel):
    username: str
    password: str

class email(BaseModel):
    email:str

class EP(BaseModel):
    email: str
    password: str

--------------------------------------

@router.post("/login", response_model=Token)
async def user_login(login_user: OAuth2PasswordRequestForm = Depends()):
    user = router.database.user.find_one({"user_name": login_user.username})

    if not user:
        return {"message: No such username exist."}
        
    verified = Hash.verify(user["password"], login_user.password)   
        
    if verified == False:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Incorrect username or password",
            headers={"WWW-Authenticate": "Bearer"},
        )
    else:
        access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
        access_token = create_access_token(
            data={"sub": user["email"]}, expires_delta=access_token_expires
        )
        return {"access_token": access_token, "token_type": "bearer"}
        
    #logout

Flutter code

  1. fastapi recieving function
  2. Onpressed
  @override
  Future save(String inputusername, String inputpassword) async {
    final Map<String, String> userDate = {
      'username': inputusername,
      'password': inputpassword,
    };

    final response = await http.post(
      Uri.parse('http://10.0.2.2:8000/user/login'),
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(userDate),
    );

    if (response.statusCode == 422) {
      print('Response body for 422 error: ${response.body}');
    } else if (response.statusCode == 200) {
      print('success');
    } else {
      // Handle other status codes
    }
  }

-----------------------------------------------

Container(
              height: 50,
              width: 250,
              decoration: BoxDecoration(
                  color: Colors.blue, borderRadius: BorderRadius.circular(20)),
              child: TextButton(
                  child: Text(
                    'Login',
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                        fontWeight: FontWeight.bold),
                  ),
                  onPressed: () {
                    if (checking()) {
                      save(usernameEditingController.text,
                          passwordEditingController.text);
                      Provider.of<UserInformationProvider>(context,
                              listen: false)
                          .changeId(
                        usernameEditingController.text,
                      );
                      Provider.of<UserInformationProvider>(context,
                              listen: false)
                          .changeId(
                        passwordEditingController.text,
                      );
                      Get.offAll(() => Homescreen());
                    }
                  }
                  // else {
                  //   print("Login Failed");
                  //   showDialog(
                  //       context: context,
                  //       builder: (BuildContext context) => AlertDialog(
                  //             title: const Text('Login Failed'),
                  //             content: const Text('Input doesn't match'),
                  //             actions: <Widget>[
                  //               TextButton(
                  //                 onPressed: () =>
                  //                     Navigator.pop(context, 'OK'),
                  //                 child: const Text('OK'),
                  //               ),
                  //             ],
                  //           ));
                  // }
                  )),

I am trying to make the login function by connecting Flutter and python(fastapi). I am using http function (without dio) in flutter, and using uvicorn to check python code.

When I tested the python code in uvicorn docs, it worked, but when I tested with Flutter emulator, it showed 422 Unprocessable Entity. I wasn't figure out the problem. Please help me...

0

There are 0 answers