Ejemplo n.º 1
0
 def test_roster_invalid_headers(self):
     """Test that invalid headers raises an error."""
     with tempfile.NamedTemporaryFile(suffix='.csv', mode='r+w') as _data:
         _data.write('first_name,middle_name\nSteve,Prefontaine')
         _data.seek(0)
         data = {'file': [_data]}
         with self.assertRaises(ValidationError):
             roster = roster_upload_validator(data)
Ejemplo n.º 2
0
    def upload_runners(self, request, *args, **kwargs):
        """Upload a CSV file for athletes to be registered into a workout

        The uploaded file must have a header row that contains the
        fields "first_name" and "last_name" and may additionally
        contain any of the fields "team", "gender", "birth_date",
        "rfid_code", or "bib_number".

        A new athlete will be created for each row in the file and that
        athlete will be added to the selected session.
        ---
        omit_serializer: true
        omit_parameters:
        - query
        - form
        parameters:
        - name: file
          description: Roster of athletes
          type: file
        """
        session = self.get_object()
        user = request.user
        roster = roster_upload_validator(request.data)
        default_team_name = 'session-{}-default-team'.format(session.pk)

        for athlete in roster:
            team_name = athlete.get('team', '').strip() or default_team_name
            team, created = Team.objects.get_or_create(name=team_name,
                                                       coach_id=user.coach.id)

            athlete_data = {
                'first_name': athlete['first_name'],
                'last_name': athlete['last_name'],
                'gender': athlete.get('gender', None),
                'birth_date': athlete.get('birth_date', '').strip() or None,
                'tfrrs_id': athlete.get('tfrrs_id', None),
                'team': team.id
            }
            serializer = AthleteSerializer(data=athlete_data)
            serializer.is_valid(raise_exception=True)
            new_athlete = serializer.create(serializer.validated_data)
            session.registered_athletes.add(new_athlete.pk)

            rfid_code = athlete.get('rfid_code', None) or None
            bib_number = athlete.get('bib_number', None) or None
            if rfid_code is not None:
                tag_data = {
                    'bib': bib_number,
                    'id_str': rfid_code,
                    'athlete': new_athlete.pk
                }
                serializer = TagSerializer(data=tag_data)
                serializer.is_valid(raise_exception=True)
                serializer.create(serializer.validated_data)

        return Response(status=status.HTTP_204_NO_CONTENT)
Ejemplo n.º 3
0
    def upload_new_names(self, request, *args, **kwargs):
        """Upload a CSV file with athletes on this team.

        The uploaded file must have a header row that contains the
        fields "first_name" and "last_name", and "new_last_name" 
        and "new_first_name" and may additionally
        contain any of the fields "gender" or "birth_date".

        A new athlete will be created for each row in the file and that
        athlete will be assigned to the current team.
        ---
        omit_serializer: true
        omit_parameters:
        - query
        - form
        parameters:
        - name: file
          description: CSV file with new name roster information
          type: file
        """
        csv_data = roster_upload_validator(request.data)
        for row in csv_data:
            # find athlete
            try:
                athlete = Athlete.objects.get(
                    user__first_name=row['first_name'],
                    user__last_name=row['last_name'],
                    tag__id_str=row['rfid_code'])
                # update name and user information
                athlete.user.first_name = row['new_first_name']
                athlete.user.last_name = row['new_last_name']
                athlete.birth_date = parse(row['new_bday'])
                print(athlete.birth_date, row['new_bday'])
                athlete.gender = row['new_gender']
                athlete.save()
                athlete.user.save()
                #
                # return Response({
                #     'name': athlete.user.first_name + " " + athlete.user.last_name,
                #     'bday': str(athlete.birth_date),
                #     'gender': athlete.gender
                # })

            except (ValueError, ObjectDoesNotExist):
                #response = "Could not find athlete with matching first_name={}, last_name={}, and rfid_tag={}".format(row['first_name', row['last_name'], row['rfid_code']])
                response = 'Could not find athlete matching name ' '{} {} {}'.format(
                    row['first_name'], row['last_name'], row['rfid_code'])
                return Response(response, status=status.HTTP_400_BAD_REQUEST)

        return Response(status=status.HTTP_204_NO_CONTENT)
Ejemplo n.º 4
0
    def upload_roster(self, request, *args, **kwargs):
        """Upload a CSV file with athletes on this team.

        The uploaded file must have a header row that contains the
        fields "first_name" and "last_name" and may additionally
        contain any of the fields "gender" or "birth_date".

        A new athlete will be created for each row in the file and that
        athlete will be assigned to the current team.
        ---
        omit_serializer: true
        omit_parameters:
        - query
        - form
        parameters:
        - name: file
          description: CSV file with roster information
          type: file
        """
        team = self.get_object()
        roster = roster_upload_validator(request.data)

        for athlete in roster:
            athlete_data = {
                'first_name': athlete['first_name'],
                'last_name': athlete['last_name'],
                'gender': athlete.get('gender', None),
                'birth_date': athlete.get('birth_date', '').strip() or None,
                'tfrrs_id': athlete.get('tfrrs_id', None),
                'team': team.pk
            }
            serializer = AthleteSerializer(data=athlete_data)
            serializer.is_valid(raise_exception=True)
            new_athlete = serializer.create(serializer.validated_data)

            rfid_code = athlete.get('rfid_code', None) or None
            bib_number = athlete.get('bib_number', None) or None
            if rfid_code is not None:
                tag_data = {
                    'bib': bib_number,
                    'id_str': rfid_code,
                    'athlete': new_athlete.pk
                }
                serializer = TagSerializer(data=tag_data)
                serializer.is_valid(raise_exception=True)
                serializer.create(serializer.validated_data)

        return Response(status=status.HTTP_204_NO_CONTENT)
Ejemplo n.º 5
0
 def test_roster_upload_xls(self):
     """Test a roster uploaded in .xls format."""
     with tempfile.NamedTemporaryFile(suffix='.xls', mode='r+w') as _data:
         book = xlwt.Workbook()
         sheet = book.add_sheet('Roster')
         rows = [('first_name', 'last_name'), ('Bill', 'Rodgers'),
                 ('Bob', 'Kennedy')]
         for n, athlete in enumerate(rows):
             sheet.write(n, 0, athlete[0])
             sheet.write(n, 1, athlete[1])
         book.save(_data)
         _data.seek(0)
         data = {'file': [_data]}
         roster = roster_upload_validator(data)
         self.assertEqual(
             roster,
             [dict(zip(rows[0], rows[1])),
              dict(zip(rows[0], rows[2]))])
Ejemplo n.º 6
0
 def test_roster_invalid_format(self):
     """Test that invalid file types raises an error."""
     with tempfile.NamedTemporaryFile(suffix='.pdf') as _data:
         data = {'file': [_data]}
         with self.assertRaises(ValidationError):
             roster = roster_upload_validator(data)