The code:
# Necessary imports are done
@app.post("/users/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
db_user = crud.get_user_by_email(db, email=user.email)
if db_user:
raise HTTPException(status_code=400, detail="Email already registered")
return crud.create_user(db=db, user=user)
The function in the given part of the documentation is giving me the "Email already taken" error, even if I post unique emails in the request body.
Managed to solve the issue by changing the function as the following:
# Necessary imports are done
@app.post("/users/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
try:
return crud.create_user(db, user)
except IntegrityError:
raise HTTPException(status_code=400, detail="Email already taken")
Here it works just fine.
Could you do me a favor?
git clone https://github.com/tiangolo/fastapicd fastapi/docs_src/sql_databases/uvicorn sql_app.main:app --reloadEnvironment:
I didn't get such an error this time but I realized that I get that issue if I change the crud.create_user function as the following (Basically I just used a real hash instead of fake hashing, the rest of the code is the same with the code in docs):
The code in the docs:
# Necessary imports are done
def create_user(db: Session, user: schemas.UserCreate):
fake_hashed_password = user.password + "notreallyhashed"
db_user = models.User(email=user.email, hashed_password=fake_hashed_password)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
My local version:
# Necessary imports are done
def create_user(db: Session, user: schemas.UserCreate):
hashed_password = sha256(user.password.encode("utf-8")).hexdigest()
db_user = models.User(email=user.email, hashed_password=hashed_password)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
Thanks for the help here @Kludex ! :clap: :bow:
Thanks for reporting back and closing the issue @umitkaanusta :+1:
Most helpful comment
Thanks for the help here @Kludex ! :clap: :bow:
Thanks for reporting back and closing the issue @umitkaanusta :+1: