def request_certificate(request):
    """Request the on-demand creation of a certificate for some user, course.
    A request doesn't imply a guarantee that such a creation will take place.
    We intentionally use the same machinery as is used for doing certification
    at the end of a course run, so that we can be sure users get graded and
    then if and only if they pass, do they get a certificate issued.
    """
    if request.method == "POST":
        if request.user.is_authenticated():
            # Enter your api key here
            xqci = CertificateGeneration(api_key="Your_API_KEY")
            username = request.user.username
            student = User.objects.get(username=username)
            course_key = SlashSeparatedCourseKey.from_deprecated_string(
                request.POST.get('course_id'))
            course = modulestore().get_course(course_key, depth=2)

            status = certificate_status_for_student(student,
                                                    course_key)['status']
            if status in [
                    CertificateStatuses.unavailable,
                    CertificateStatuses.notpassing, CertificateStatuses.error
            ]:
                logger.info(
                    'Grading and certification requested for user {} in course {} via /request_certificate call'
                    .format(username, course_key))
                status = xqci.add_cert(student, course_key, course=course)
            return HttpResponse(json.dumps({'add_status': status}),
                                mimetype='application/json')
        return HttpResponse(json.dumps({'add_status': 'ERRORANONYMOUSUSER'}),
                            mimetype='application/json')
    def handle(self, *args, **options):

        # Will only generate a certificate if the current
        # status is in the unavailable state, can be set
        # to something else with the force flag

        if options['force']:
            valid_statuses = getattr(CertificateStatuses, options['force'])
        else:
            valid_statuses = [CertificateStatuses.unavailable]

        if options['course']:
            # try to parse out the course from the serialized form
            try:
                course = CourseKey.from_string(options['course'])
            except InvalidKeyError:
                print(
                    "Course id {} could not be parsed as a CourseKey; falling back to SSCK.from_dep_str"
                    .format(options['course']))
                course = SlashSeparatedCourseKey.from_deprecated_string(
                    options['course'])
            ended_courses = [course]
        else:
            raise CommandError("You must specify a course")
        if options['api_key']:
            api_key = options['api_key']
        else:
            raise CommandError(
                "You must give a api_key, if don't have one visit: https://accredible.com/issuer/sign_up"
            )
        if options['styling']:
            if options['styling'] == 'True':
                new_status = "generating"
            else:
                raise CommandError(
                    "You must give true if want to do styling, no any other argument"
                )
        else:
            new_status = "downloadable"
        for course_key in ended_courses:
            # prefetch all chapters/sequentials by saying depth=2
            course = modulestore().get_course(course_key, depth=2)
            print "Fetching enrolled students for {0}".format(
                course_key.to_deprecated_string())
            enrolled_students = User.objects.filter(
                courseenrollment__course_id=course_key)
            xq = CertificateGeneration(api_key=api_key)
            total = enrolled_students.count()
            print "Total number of students: " + str(total)
            for student in enrolled_students:
                if certificate_status_for_student(
                        student, course_key)['status'] in valid_statuses:
                    ret = xq.add_cert(student,
                                      course_key,
                                      new_status,
                                      course=course)
                    print ret
    def handle(self, *args, **options):

        # Will only generate a certificate if the current
        # status is in the unavailable state, can be set
        # to something else with the force flag

        if options['force']:
            valid_statuses = getattr(CertificateStatuses, options['force'])
        else:
            valid_statuses = [CertificateStatuses.unavailable]

        if options['course']:
            # try to parse out the course from the serialized form
            try:
                course = CourseKey.from_string(options['course'])
            except InvalidKeyError:
                print("Course id {} could not be parsed as a CourseKey; falling back to SSCK.from_dep_str".format(options['course']))
                course = SlashSeparatedCourseKey.from_deprecated_string(options['course'])
            ended_courses = [course]
        else:
            raise CommandError("You must specify a course")
        
        if options['api_key']:
            api_key = options['api_key']
        else:
            raise CommandError("You must give a api_key, if don't have one visit: https://accredible.com/issuer/sign_up")

        if options['styling']:
            if options['styling'] == 'True': 
                new_status = "generating"
            else:
                raise CommandError("You must give true if want to do no styling, no any other argument")
        else:
            new_status = "downloadable"


        for course_key in ended_courses:
            # prefetch all chapters/sequentials by saying depth=2
            course = modulestore().get_course(course_key, depth=2)

            print "Fetching enrolled students for {0}".format(course_key.to_deprecated_string())
            enrolled_students = User.objects.filter(
                courseenrollment__course_id=course_key)

            xq = CertificateGeneration(api_key=api_key)
            total = enrolled_students.count()
            print "Total number of students: " + str(total) 
            for student in enrolled_students:
                if certificate_status_for_student(
                    student, course_key)['status'] in valid_statuses:
                      ret = xq.add_cert(student, course_key, new_status, course=course)
                      print ret
def request_certificate(request):
    """Request the on-demand creation of a certificate for some user, course.
    A request doesn't imply a guarantee that such a creation will take place.
    We intentionally use the same machinery as is used for doing certification
    at the end of a course run, so that we can be sure users get graded and
    then if and only if they pass, do they get a certificate issued.
    """
    if request.method == "POST":
        if request.user.is_authenticated():
            # Enter your api key here
            xqci = CertificateGeneration(api_key="Your_API_KEY")
            username = request.user.username
            student = User.objects.get(username=username)
            course_key = SlashSeparatedCourseKey.from_deprecated_string(request.POST.get('course_id'))
            course = modulestore().get_course(course_key, depth=2)

            status = certificate_status_for_student(student, course_key)['status']
            if status in [CertificateStatuses.unavailable, CertificateStatuses.notpassing, CertificateStatuses.error]:
                logger.info('Grading and certification requested for user {} in course {} via /request_certificate call'.format(username, course_key))
                status = xqci.add_cert(student, course_key, course=course)
            return HttpResponse(json.dumps({'add_status': status}), mimetype='application/json')
        return HttpResponse(json.dumps({'add_status': 'ERRORANONYMOUSUSER'}), mimetype='application/json')