Skip to content

Instantly share code, notes, and snippets.

@lgp171188
Created September 20, 2018 19:27
Show Gist options
  • Save lgp171188/f546c1cdb739aae6dfa29775b1e04ac5 to your computer and use it in GitHub Desktop.
Save lgp171188/f546c1cdb739aae6dfa29775b1e04ac5 to your computer and use it in GitHub Desktop.
from opaque_keys import InvalidKeyError
from opaque_keys.edx.location import SlashSeparatedCourseKey
from django import forms
from django.core.exceptions import ValidationError
class UsersInCohortApiListForm(forms.Form):
course_key_string = forms.CharField()
cohort_id = forms.IntegerField()
def clean_course_key_string(self):
course_key_string = self.cleaned_data['course_key_string']
try:
return SlashSeparatedCourseKey.from_deprecated_string(course_key_string)
except InvalidKeyError:
raise ValidationError('{} is not a valid course key'.format(course_key_string))
from rest_framework import serializers
from django.contrib.auth.models import User
class UsersInCohortSerializer(serializers.ModelSerializer):
name = serializers.SerializerMethodField('get_full_name')
def get_full_name(self, instance):
return '{} {}'.format(instance.first_name, instance.last_name)
class Meta:
model = User
fields = ('username', 'email', 'name')
from rest_framework.generics import ListAPIView
from django.core.exceptions import ValidationError
from django.http import Http404
from openedx.core.lib.api.view_utils import DeveloperErrorViewMixin, view_auth_classes
from .cohorts import get_cohort_by_id
from .forms import UsersInCohortApiListForm
from .models import CourseUserGroup
from .serializers import UsersInCohortSerializer
@view_auth_classes()
class UsersInCohortApiListView(DeveloperErrorViewMixin, ListAPIView):
"""
TODO:
"""
permission_classes = IsAdminUser,
throttle_classes = [] # TBD
serializer_class = UsersInCohortSerializer
def get_queryset(self):
form = UsersInCohortApiListForm(self.kwargs)
if not form.is_valid():
raise ValidationError(form.errors)
course_key = form.cleaned_data['course_key_string']
cohort_id = form.cleaned_data['cohort_id']
try:
cohort = get_cohort_by_id(course_key, cohort_id)
except CourseUserGroup.DoesNotExist:
raise Http404
return cohort.users.all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment