From 5ecc7ea615b3a3d3b84fd99b3f804cab3b0bdab0 Mon Sep 17 00:00:00 2001 From: Colin Bassett Date: Tue, 25 Feb 2025 12:29:26 -0500 Subject: [PATCH] Implement an update to the create function to not allow duplicate emails --- api.py | 4 ++++ sql.py | 4 +++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/api.py b/api.py index 271e2b8..9c09572 100644 --- a/api.py +++ b/api.py @@ -17,6 +17,10 @@ app = FastAPI(lifespan=lifespan) # Routes @app.post("/heroes/create", response_model=HeroPublic) def create_hero(hero: HeroCreate, session: SessionDep): + existing_hero = session.query(Hero).filter(Hero.email == hero.email).first() + if existing_hero: + raise HTTPException(status_code=400, detail="Email already registered") + db_hero = Hero.model_validate(hero) session.add(db_hero) session.commit() diff --git a/sql.py b/sql.py index 9447238..8d336d6 100644 --- a/sql.py +++ b/sql.py @@ -2,6 +2,8 @@ from typing import Annotated from fastapi import Depends from sqlmodel import Field, Session, SQLModel, create_engine +from sqlalchemy import String +from sqlalchemy.sql.schema import Column # The base hero class class HeroBase(SQLModel): @@ -12,7 +14,7 @@ class HeroBase(SQLModel): # The main hero class. It inherits the name, gold, and health class Hero(HeroBase, table=True): id: int | None = Field(default=None, primary_key=True, index=True) - email: str = Field(index=True) + email: str = Field(index=True, unique=True) password: str salt: int