Пример #1
0
def import_enrollments(request):
    status = []
    if request.method == "POST":
        # Convert JSON data to Python object
        data = json.loads(request.raw_post_data)

        validate_credentials(request, settings.API_ALLOWED_HOSTS, settings.API_KEY, data[0].get("api_key", ""))

        # Redefine data variable to actual enrollment list
        data = data[0]["enrollments"]

        # Let's keep a count of how many new and updated objects we have
        enrollments_updated = 0
        enrollments_created = 0

        # Grab all existing sections, users, and enrollments as well as
        # their associated objects from the database
        all_sections = Section.objects.filter(term=settings.CURRENT_TERM, year=settings.CURRENT_YEAR)
        all_users = UserProfile.objects.filter(user__groups__name="Students").select_related()
        all_enrollments = Enrollment.objects.filter(
            section__term=settings.CURRENT_TERM, section__year__exact=settings.CURRENT_YEAR
        )

        for e in data:
            section_exists = True
            try:
                section = all_sections.filter(prefix=e["prefix"], number=e["number"], section=e["section"])[0]
            except IndexError:
                status.append("Section (%s%s-%s) does not exist" % (e["prefix"], e["number"], e["section"]))
                section_exists = False

            student_exists = True
            try:
                student = all_users.filter(id_number=e["student"])[0].user
            except IndexError:
                status.append("Student (ID number %s) " "does not exist" % e["student"])
                student_exists = False

            if section_exists and student_exists:
                new_enrollment = False
                try:
                    enrollment = all_enrollments.filter(section=section, student=student)[0]
                except IndexError:
                    enrollment = Enrollment(student=student, section=section)
                    new_enrollment = True

                if new_enrollment:
                    enrollments_created += 1
                else:
                    enrollments_updated += 1

                # Only update metadata for enrollment if changed
                if enrollment.status != e["status"]:
                    enrollment.status = e["status"]
                    enrollment.save()
                elif new_enrollment:
                    enrollment.save()

        status.append("Received %d enrollment records" % len(data))
        status.append("Updated %d enrollment objects" % enrollments_updated)
        status.append("Created %d enrollment objects" % enrollments_created)
    else:
        status.append("Invalid request")

    return HttpResponse("\n".join(status), mimetype="text/plain")
Пример #2
0
def import_enrollments(request):
    status = []
    if request.method == 'POST':
        # Convert JSON data to Python object
        data = json.loads(request.raw_post_data)

        validate_credentials(request,
                             settings.API_ALLOWED_HOSTS,
                             settings.API_KEY,
                             data[0].get('api_key', ''))

        # Redefine data variable to actual enrollment list
        data = data[0]['enrollments']

        # Let's keep a count of how many new and updated objects we have
        enrollments_updated = 0
        enrollments_created = 0

        # Grab all existing sections, users, and enrollments as well as
        # their associated objects from the database
        existing_sections = get_existing_sections(settings.CURRENT_TERM,
                                                  settings.CURRENT_YEAR)

        id_numbers = []
        for e in data:
            id_numbers.append(e['student'])

        existing_users = get_existing_users(['Students'], id_numbers)
        existing_enrollments = get_existing_enrollments(settings.CURRENT_TERM,
                                                        settings.CURRENT_YEAR)

        for e in data:
            key = '%s%s-%s-%s-%d' % (e['prefix'],
                                     e['number'],
                                     e['section'],
                                     e['term'],
                                     int(e['year']))
            section = existing_sections.get(key)

            section_exists = True
            if not section:
                status.append('Section (%s%s-%s) does not exist' % (
                    e['prefix'],
                    e['number'],
                    e['section']))
                section_exists = False

            student = existing_users.get(e['student'])

            student_exists = True
            if not student:
                status.append('Student (ID number %s) '
                              'does not exist' % e['student'])
                student_exists = False

            if section_exists and student_exists:
                key = '%s-%s%s-%s-%s-%d' % (e['student'],
                                            e['prefix'],
                                            e['number'],
                                            e['section'],
                                            e['term'],
                                            int(e['year']))
                enrollment = existing_enrollments.get(key)

                new_enrollment = False
                if not enrollment:
                    enrollment = Enrollment(student=student, section=section)
                    new_enrollment = True

                if new_enrollment:
                    enrollments_created += 1
                else:
                    enrollments_updated += 1


                # Only update metadata for enrollment if changed
                if enrollment.status != e['status']:
                    enrollment.status = e['status']
                    enrollment.save()
                elif new_enrollment:
                    enrollment.save()

        status.append('Received %d enrollment records' % len(data))
        status.append('Updated %d enrollment objects' % enrollments_updated)
        status.append('Created %d enrollment objects' % enrollments_created)
    else:
        status.append('Invalid request')

    return HttpResponse('\n'.join(status), mimetype='text/plain')