Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
3.0 kB
4
Indexable
Never
#PLAYERS
class PlayerCreate(BaseModel):
    player_id: int
    player_name: str
    player_bday: date
    player_club: int
    player_pos: str
    player_nation : str
    js_number : int
    show: bool = True

@app.post("/add_players")
async def add_players(player: PlayerCreate, db: Session = Depends(get_db)):
    try:
        newPlayerDict = player.dict()
        for key, value in newPlayerDict.items():
            if value == "string":
                return {"message": f"{key} is required."}
            if key == "player_bday" and not isValidAge(value):
                return {"message": "User age is not legal"}

        count = db.query(func.max(models.Players.player_id)).scalar()
        newPlayerDict['player_id'] = (count or 0) + 1
        new_db_player = models.Players(**newPlayerDict)

        db.add(new_db_player)
        db.commit()
        db.refresh(new_db_player)
        return new_db_player
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"Internal Server Error: {str(e)}")

class PlayerShow(BaseModel):
    player_name: str
    player_bday: date
    player_club: int
    player_pos: str
    player_nation : str
    js_number : int
    
@app.get('/get_players', response_model=List[PlayerShow])
async def get_players_by_name(full_name: str, db: Session = Depends(get_db), threshold: int = 80):
    try:
        # Query only players where show is True
        players = db.query(models.Players).filter(models.Players.show == True).all()
        # Filter players based on the fuzzy match threshold
        matched_players = [player for player in players if fuzz.partial_ratio(player.player_name.lower(), full_name.lower()) >= threshold]
        if not matched_players:
            raise HTTPException(status_code=404, detail='Cannot find players')
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal Server Error: {str(e)}")
    return matched_players

class PlayerUpdate(BaseModel):
    player_name: str
    player_bday: date
    player_club: int
    js_number: int
    player_pos: str
    show : bool = True

@app.put("/update_player")
async def update_player(playerID: int, player_update : PlayerUpdate, db: db_dependency):
    try: 
        target = db.query(models.Players).filter(models.Players.player_id == playerID).first()
        
        update_info = player_update.dict(exclude_unset=True)

        for key, value in update_info.items(): 
            if value == "string":
                return {"message": f"{key} is required."}
            if key == "player_bday" and not isValidAge(value):
                return {"message": "User age is not legal"}
            setattr(target, key, value)
        db.commit()
        db.refresh(target)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Internal Server Error: {str(e)}!")
    return target
    
Leave a Comment