Flutter(front) & Python(back) connection: 404 Not found error (uvicorn), login function making

78 Views Asked by At

The following is python code for login function:

  1. user model
  2. login fastapi
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

The following code is flutter code:

  1. function
  2. receiving
  Future<Map> saveTwo(
    String inputusername,
    String inputpassword,
  ) async {
    final Map<String, String> userData = {
      'user_name': inputusername,
      'password': inputpassword,
    };

    final response = await Dio().post(
      'http://10.0.2.2:8000/users/login',
      data: jsonEncode(userData),
    );

    //     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(userData),
    // );

    if (response.statusCode == 401) {
      print('Response body for 401 error: ${response.data}');
    } else if (response.statusCode == 404) {
      print('Response body for 404 error: ${response.data}');
    } else if (response.statusCode == 200) {
      print('success');
    } else {
      print("other error");
    }

    return response.data;
  }
          FutureBuilder(
              future: saveTwo(usernameEditingController.text,
                  passwordEditingController.text),
              builder: (context, snapshot) {
                return Container(
                    height: 50,
                    width: 250,
                    decoration: BoxDecoration(
                        color: Colors.blue,
                        borderRadius: BorderRadius.circular(20)),
                    child: TextButton(
                        onPressed: () {
                          print(snapshot.data.toString());
                          if (checking()) {
                            switch (snapshot.data) {
                              case "message: No such username exist.":
                                showDialog(
                                    context: context,
                                    builder: (BuildContext context) =>
                                        AlertDialog(
                                          title: const Text('Login failed'),
                                          content:
                                              const Text('Password is not match'),
                                          actions: <Widget>[
                                            TextButton(
                                              onPressed: () =>
                                                  Navigator.pop(context, 'OK'),
                                              child: const Text('OK'),
                                            ),
                                          ],
                                        ));
                                break;
                              default:
                                Provider.of<UserInformationProvider>(context,
                                        listen: false)
                                    .changeId(
                                  usernameEditingController.text,
                                );
                                Provider.of<UserInformationProvider>(context,
                                        listen: false)
                                    .changeId(
                                  passwordEditingController.text,
                                );
                                Get.offAll(() => Homescreen());
                            }
                          } else {
                            showDialog(
                              context: context,
                              builder: (BuildContext context) => AlertDialog(
                                title: const Text('Input error'),
                                content: const Text('Please type all the value.'),
                                actions: <Widget>[
                                  TextButton(
                                    onPressed: () =>
                                        Navigator.pop(context, 'OK'),
                                    child: const Text('OK'),
                                  ),
                                ],
                              ),
                            );
                          }

                          // if (checking()) {
                          //   save(
                          //     usernameEditingController.text,
                          //     passwordEditingController.text,
                          //   );
                          //   print('##### Token information : ${save(
                          //     usernameEditingController.text,
                          //     passwordEditingController.text,
                          //   ).toString()} #####');
                          //   Provider.of<UserInformationProvider>(context, listen: false)
                          //       .changeId(
                          //     usernameEditingController.text,
                          //   );
                          //   Provider.of<UserInformationProvider>(context, listen: false)
                          //       .changeId(
                          //     passwordEditingController.text,
                          //   );
                          //   Get.offAll(() => Homescreen());
                          // } else {
                          //   showDialog(
                          //     context: context,
                          //     builder: (BuildContext context) => AlertDialog(
                          //       title: const Text('Input error'),
                          //       content: const Text('Please type all the value.'),
                          //       actions: <Widget>[
                          //         TextButton(
                          //           onPressed: () => Navigator.pop(context, 'OK'),
                          //           child: const Text('OK'),
                          //         ),
                          //       ],
                          //     ),
                          //   );
                          // }
                        },
                        child: Text(
                          'Login',
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 20,
                              fontWeight: FontWeight.bold),
                        )));
              }),

Through flutter, I am sending id, pw through dio, post method. But the response showed the 404 not found error. I don't know wheter I should authorize my flutter emulator or not.

0

There are 0 best solutions below