Fastapi: Function create_user in Docs/Tutorial/SQL (Relational) Databases not working

Created on 5 Aug 2020  路  3Comments  路  Source: tiangolo/fastapi

Example

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)

Description

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.

  • Checked my version of schemas.py, models.py and database.py
  • Using yield dependencies since I have Python 3.7

Environment

  • OS: Windows 10 Home
  • FastAPI Version: 0.60.1
  • Python version: 3.7.4

Additional context

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")
question

Most helpful comment

Thanks for the help here @Kludex ! :clap: :bow:

Thanks for reporting back and closing the issue @umitkaanusta :+1:

All 3 comments

Here it works just fine.

Could you do me a favor?

  1. Clone: git clone https://github.com/tiangolo/fastapi
  2. Go to the example folder: cd fastapi/docs_src/sql_databases/
  3. Run the example with uvicorn: uvicorn sql_app.main:app --reload
  4. Check if you're still having the issue.

Environment:

  • OS: Ubuntu 20.04
  • FastAPI version: 0.60.1
  • Python version: 3.8.3

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:

Was this page helpful?
0 / 5 - 0 ratings