コード例 #1
0
async def update_competitors(
        tournament_id: int,
        competitors: List[CompetitorCreate],
        tournament: Tournament = Depends(alterable_tournament),
        db: Session = Depends(get_db),
):
    if not tournament:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f'No tournament found with id {tournament_id}',
        )
    else:
        # Delete all the existing competitors and create new ones
        tournament.delete_competitors(db, autocommit=False)
        try:
            Competitor.create_batch(tournament, competitors, db, autocommit=False)
        except IntegrityError:
            db.rollback()
            raise HTTPException(
                status_code=status.HTTP_409_CONFLICT,
                detail='Competitors must have at least a last name or an organization',
            )
        else:
            db.commit()
            db.refresh(tournament)
            return tournament.competitors
コード例 #2
0
async def visible_tournament(
        tournament_id: int,
        current_user: Optional[User] = Depends(
            get_current_active_user_or_none),
        db: Session = Depends(get_db),
) -> Optional[Tournament]:
    return Tournament.by_id_visible(tournament_id, current_user, db)
コード例 #3
0
async def create_tournament_status(
        tournament_id: int,
        status_data: Status,
        tournament: Tournament = Depends(alterable_tournament),
        current_user: User = Depends(get_current_active_user),
        db: Session = Depends(get_db),
):
    if tournament:
        tournament.change_status(status_data.status, db)
        return tournament
    else:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=
            f'No editable tournament found with id {tournament_id} for user {current_user.email}',
        )
コード例 #4
0
async def delete_tournament(
        tournament_id: int,
        tournament: Tournament = Depends(alterable_tournament),
        current_user: User = Depends(get_current_active_user),
        db: Session = Depends(get_db),
):
    """
    Deletes the desired tournament if the current user owns it
    """
    if tournament:
        tournament.delete(db)
    else:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=
            f'No editable tournament found with id {tournament_id} for user {current_user.email}',
        )
コード例 #5
0
async def create_tournament(
        tournament: TournamentCreate,
        current_user: User = Depends(get_current_active_user),
        db: Session = Depends(get_db),
):
    """
    Creates a new tournament owned by the current user
    """
    return Tournament.create(tournament, current_user, db)
コード例 #6
0
async def get_tournaments(
        is_filtered_by_user: bool = False,
        skip: int = 0,
        limit: int = 100,
        current_user: Optional[User] = Depends(
            get_current_active_user_or_none),
        db: Session = Depends(get_db),
):
    """
    Return all public tournaments and any private tournaments owned by the current_user, if present
    """
    tournament_count = len(
        Tournament.get_all_visible(current_user, db, is_filtered_by_user))
    tournaments = Tournament.get_all_visible(current_user, db,
                                             is_filtered_by_user, skip, limit)
    return {
        'total': tournament_count,
        'items': tournaments,
    }
コード例 #7
0
ファイル: stage.py プロジェクト: ianwestfall/tourneyman-fast
async def update_stages(
        tournament_id: int,
        stages: List[StageCreate],
        tournament: Tournament = Depends(alterable_tournament),
        db: Session = Depends(get_db),
):
    if not tournament:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f'No tournament found with id {tournament_id}',
        )
    else:
        tournament.delete_stages(db, autocommit=False)

        for stage in stages:
            tournament.stages += [
                Stage.create(tournament, stage, db, autocommit=False)
            ]

        db.commit()
        db.refresh(tournament)
        return tournament.stages
コード例 #8
0
def update():
    logger = getLogger("cronjob.tourney")
    logger.info("Updating Tournament database...")

    repo_path = environ["TOURNEY_REPO"]
    repository = Path(repo_path)
    if not repository.is_dir():
        logger.critical("Repository path %s is not a valid directory.",
                        repository)
        raise NotADirectoryError(str(repository))

    logger.info("Pulling repository changes...")
    call(["git", "pull", "-q"],
         cwd=str(repository),
         stdout=DEVNULL,
         stderr=DEVNULL)

    tourney_base = repository / "tournaments"
    if not tourney_base.is_dir():
        logger.critical("Tournament base %s is not a valid directory.",
                        tourney_base)
        raise NotADirectoryError(str(tourney_base))

    logger.info("Reading tournament event files...")
    event_json_files = (json for json in tourney_base.glob("**/*.json")
                        if json.is_file())

    logger.info("Updating tournament database...")
    session = Session()

    paths = list()
    for event_json_file in event_json_files:
        relative = event_json_file.relative_to(tourney_base)
        paths.append(str(relative))
        logger.debug("Handling file %s.", relative)
        with event_json_file.open() as event_json:
            raw = event_json.read()
            hash = md5(raw.encode("utf-8")).hexdigest()
            tourney_data = loads(raw)
        logger.debug("Read JSON data, file hash: %s.", hash)
        tourney_date = datetime.strptime(tourney_data["date"], STRP_FORMAT)

        try:
            tourney = (session.query(Tournament).filter(
                Tournament.path == str(relative)).one())
        except NoResultFound:
            tourney = Tournament(tourney_data["title"], tourney_date,
                                 tourney_data["winner"], tourney_data["mode"],
                                 tourney_data["url"], str(relative), hash)

            session.add(tourney)
            logger.debug("Created new tourney: {0}".format(tourney))
        else:
            # check if hash has changed
            if tourney.md5_hash != hash:
                tourney.md5_hash = hash
                tourney.title = tourney_data["title"]
                tourney.date = tourney_date
                tourney.winner = tourney_data["winner"]
                tourney.mode = tourney_data["mode"]
                tourney.url = tourney_data["url"]
                session.add(tourney)

    session.commit()

    # remove tournaments no longer in the repo
    obsolete_tourneys = (session.query(Tournament).filter(
        Tournament.path.notin_(paths)).all())
    for obsolete_tourney in obsolete_tourneys:
        logger.info("Purged tourney {0} which is no longer present in the "
                    "repository".format(obsolete_tourney))
        session.delete(obsolete_tourney)

    session.commit()
    session.close()
コード例 #9
0
 def up(self, tournament: Tournament, db: Session):
     """
     The first stage should be initialized
     """
     tournament.progress(db, autocommit=False)