当前位置: 首页>>代码示例>>Python>>正文


Python SlashSeparatedCourseKey.from_deprecated_string方法代码示例

本文整理汇总了Python中xmodule.modulestore.locations.SlashSeparatedCourseKey.from_deprecated_string方法的典型用法代码示例。如果您正苦于以下问题:Python SlashSeparatedCourseKey.from_deprecated_string方法的具体用法?Python SlashSeparatedCourseKey.from_deprecated_string怎么用?Python SlashSeparatedCourseKey.from_deprecated_string使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在xmodule.modulestore.locations.SlashSeparatedCourseKey的用法示例。


在下文中一共展示了SlashSeparatedCourseKey.from_deprecated_string方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: handle

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
    def handle(self, *args, **options):
        source_key = SlashSeparatedCourseKey.from_deprecated_string(options['source_course'])
        dest_key = SlashSeparatedCourseKey.from_deprecated_string(options['dest_course'])

        source_students = User.objects.filter(
            courseenrollment__course_id=source_key
        )

        for user in source_students:
            if CourseEnrollment.is_enrolled(user, dest_key):
                # Un Enroll from source course but don't mess
                # with the enrollment in the destination course.
                CourseEnrollment.unenroll(user, source_key)
                print("Unenrolled {} from {}".format(user.username, source_key.to_deprecated_string()))
                msg = "Skipping {}, already enrolled in destination course {}"
                print(msg.format(user.username, dest_key.to_deprecated_string()))
                continue

            print("Moving {}.".format(user.username))
            # Find the old enrollment.
            enrollment = CourseEnrollment.objects.get(
                user=user,
                course_id=source_key
            )

            # Move the Student between the classes.
            mode = enrollment.mode
            old_is_active = enrollment.is_active
            CourseEnrollment.unenroll(user, source_key)
            new_enrollment = CourseEnrollment.enroll(user, dest_key, mode=mode)

            # Unenroll from the new coures if the user had unenrolled
            # form the old course.
            if not old_is_active:
                new_enrollment.update_enrollment(is_active=False)

            if mode == 'verified':
                try:
                    certificate_item = CertificateItem.objects.get(
                        course_id=source_key,
                        course_enrollment=enrollment
                    )
                except CertificateItem.DoesNotExist:
                    print("No certificate for {}".format(user))
                    continue

                certificate_item.course_id = dest_key
                certificate_item.course_enrollment = new_enrollment
                certificate_item.save()
开发者ID:PaoloC68,项目名称:edx-platform,代码行数:51,代码来源:transfer_students.py

示例2: process_request

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
    def process_request(self, request):
        """
        Add a user's tags to the tracking event context.
        """
        match = COURSE_REGEX.match(request.build_absolute_uri())
        course_id = None
        if match:
            course_id = match.group('course_id')
            course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)

        context = {}

        if course_id:
            context['course_id'] = course_id

            if request.user.is_authenticated():
                context['course_user_tags'] = dict(
                    UserCourseTag.objects.filter(
                        user=request.user.pk,
                        course_id=course_key,
                    ).values_list('key', 'value')
                )
            else:
                context['course_user_tags'] = {}

        tracker.get_tracker().enter_context(
            self.CONTEXT_NAME,
            context
        )
开发者ID:PaoloC68,项目名称:edx-platform,代码行数:31,代码来源:middleware.py

示例3: show_unit_extensions

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
def show_unit_extensions(request, course_id):
    """
    Shows all of the students which have due date extensions for the given unit.
    """
    course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
    unit = find_unit(course, request.GET.get('url'))
    return JsonResponse(dump_module_extensions(course, unit))
开发者ID:PaoloC68,项目名称:edx-platform,代码行数:9,代码来源:api.py

示例4: handle

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
    def handle(self, *args, **options):

        dry_run = options['dry_run']
        task_number = options['task_number']

        if len(args) == 4:
            course_id = SlashSeparatedCourseKey.from_deprecated_string(args[0])
            location = course_id.make_usage_key_from_deprecated_string(args[1])
            students_ids = [line.strip() for line in open(args[2])]
            hostname = args[3]
        else:
            print self.help
            return

        try:
            course = get_course(course_id)
        except ValueError as err:
            print err
            return

        descriptor = modulestore().get_item(location, depth=0)
        if descriptor is None:
            print "Location not found in course"
            return

        if dry_run:
            print "Doing a dry run."

        students = User.objects.filter(id__in=students_ids).order_by('username')
        print "Number of students: {0}".format(students.count())

        for student in students:
            post_submission_for_student(student, course, location, task_number, dry_run=dry_run, hostname=hostname)
开发者ID:aemilcar,项目名称:edx-platform,代码行数:35,代码来源:openended_post.py

示例5: handle

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
    def handle(self, *args, **options):
        if not options['course_id']:
            raise CommandError("You must specify a course id for this command")
        if not options['from_mode'] or not options['to_mode']:
            raise CommandError('You must specify a "to" and "from" mode as parameters')

        try:
            course_key = CourseKey.from_string(options['course_id'])
        except InvalidKeyError:
            course_key = SlashSeparatedCourseKey.from_deprecated_string(options['course_id'])

        filter_args = dict(
            course_id=course_key,
            mode=options['from_mode']
        )
        if options['user']:
            if '@' in options['user']:
                user = User.objects.get(email=options['user'])
            else:
                user = User.objects.get(username=options['user'])
            filter_args['user'] = user
        enrollments = CourseEnrollment.objects.filter(**filter_args)
        if options['noop']:
            print "Would have changed {num_enrollments} students from {from_mode} to {to_mode}".format(
                num_enrollments=enrollments.count(),
                from_mode=options['from_mode'],
                to_mode=options['to_mode']
            )
        else:
            for enrollment in enrollments:
                enrollment.update_enrollment(mode=options['to_mode'])
                enrollment.save()
开发者ID:PaoloC68,项目名称:edx-platform,代码行数:34,代码来源:change_enrollment.py

示例6: handle

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("course_id not specified")

        # Get the modulestore

        try:
            name = options["modulestore"]
            store = modulestore(name)
        except KeyError:
            raise CommandError("Unknown modulestore {}".format(name))

        # Get the course data

        try:
            course_id = SlashSeparatedCourseKey.from_deprecated_string(args[0])
        except InvalidKeyError:
            raise CommandError("Invalid course_id")

        course = store.get_course(course_id)
        if course is None:
            raise CommandError("Invalid course_id")

        # precompute inherited metadata at the course level, if needed:
        if options["inherited"]:
            compute_inherited_metadata(course)

        # Convert course data to dictionary and dump it as JSON to stdout

        info = dump_module(course, inherited=options["inherited"], defaults=options["inherited_defaults"])

        return json.dumps(info, indent=2, sort_keys=True)
开发者ID:nanolearning,项目名称:edx-platform,代码行数:34,代码来源:dump_course_structure.py

示例7: remove_user_from_cohort

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
def remove_user_from_cohort(request, course_key, cohort_id):
    """
    Expects 'username': username in POST data.

    Return json dict of:

    {'success': True} or
    {'success': False,
     'msg': error_msg}
    """
    # this is a string when we get it here
    course_key = SlashSeparatedCourseKey.from_deprecated_string(course_key)
    get_course_with_access(request.user, 'staff', course_key)

    username = request.POST.get('username')
    if username is None:
        return json_http_response({'success': False,
                                   'msg': 'No username specified'})

    cohort = cohorts.get_cohort_by_id(course_key, cohort_id)
    try:
        user = User.objects.get(username=username)
        cohort.users.remove(user)
        return json_http_response({'success': True})
    except User.DoesNotExist:
        log.debug('no user')
        return json_http_response({'success': False,
                                   'msg': "No user '{0}'".format(username)})
开发者ID:PaoloC68,项目名称:edx-platform,代码行数:30,代码来源:views.py

示例8: static_tab

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
def static_tab(request, course_id, tab_slug):
    """
    Display the courses tab with the given name.

    Assumes the course_id is in a valid format.
    """
    course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_with_access(request.user, 'load', course_key)

    tab = CourseTabList.get_tab_by_slug(course.tabs, tab_slug)
    if tab is None:
        raise Http404

    contents = get_static_tab_contents(
        request,
        course,
        tab
    )
    if contents is None:
        raise Http404

    return render_to_response('courseware/static_tab.html', {
        'course': course,
        'tab': tab,
        'tab_contents': contents,
    })
开发者ID:PaoloC68,项目名称:edx-platform,代码行数:28,代码来源:views.py

示例9: parse_args

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
    def parse_args(self, *args):
        """
        Return a 4-tuple of (course_key, user, org, offering).
        If the user didn't specify an org & offering, those will be None.
        """
        if len(args) < 2:
            raise CommandError(
                "migrate_to_split requires at least two arguments: "
                "a course_key and a user identifier (email or ID)"
            )

        try:
            course_key = CourseKey.from_string(args[0])
        except InvalidKeyError:
            course_key = SlashSeparatedCourseKey.from_deprecated_string(args[0])

        try:
            user = user_from_str(args[1])
        except User.DoesNotExist:
            raise CommandError("No user found identified by {}".format(args[1]))

        try:
            org = args[2]
            offering = args[3]
        except IndexError:
            org = offering = None

        return course_key, user, org, offering
开发者ID:PaoloC68,项目名称:edx-platform,代码行数:30,代码来源:migrate_to_split.py

示例10: spoc_gradebook

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
def spoc_gradebook(request, course_id):
    """
    Show the gradebook for this course:
    - Only shown for courses with enrollment < settings.FEATURES.get("MAX_ENROLLMENT_INSTR_BUTTONS")
    - Only displayed to course staff
    """
    course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    course = get_course_with_access(request.user, 'staff', course_key, depth=None)

    enrolled_students = User.objects.filter(
        courseenrollment__course_id=course_key,
        courseenrollment__is_active=1
    ).order_by('username').select_related("profile")

    # possible extension: implement pagination to show to large courses

    student_info = [
        {
            'username': student.username,
            'id': student.id,
            'email': student.email,
            'grade_summary': student_grades(student, request, course),
            'realname': student.profile.name,
        }
        for student in enrolled_students
    ]

    return render_to_response('courseware/gradebook.html', {
        'students': student_info,
        'course': course,
        'course_id': course_key,
        # Checked above
        'staff_access': True,
        'ordered_grades': sorted(course.grade_cutoffs.items(), key=lambda i: i[1], reverse=True),
    })
开发者ID:aemilcar,项目名称:edx-platform,代码行数:37,代码来源:api.py

示例11: handle

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
    def handle(self, *args, **options):
        if len(args) != 1:
            raise CommandError("Usage: unique_id_mapping %s" %
                               " ".join(("<%s>" % arg for arg in Command.args)))

        course_key = SlashSeparatedCourseKey.from_deprecated_string(args[0])

        # Generate the output filename from the course ID.
        # Change slashes to dashes first, and then append .csv extension.
        output_filename = course_key.to_deprecated_string().replace('/', '-') + ".csv"

        # Figure out which students are enrolled in the course
        students = User.objects.filter(courseenrollment__course_id=course_key)
        if len(students) == 0:
            self.stdout.write("No students enrolled in %s" % course_key.to_deprecated_string())
            return

        # Write mapping to output file in CSV format with a simple header
        try:
            with open(output_filename, 'wb') as output_file:
                csv_writer = csv.writer(output_file)
                csv_writer.writerow((
                    "User ID",
                    "Per-Student anonymized user ID",
                    "Per-course anonymized user id"
                ))
                for student in students:
                    csv_writer.writerow((
                        student.id,
                        anonymous_id_for_user(student, None),
                        anonymous_id_for_user(student, course_key)
                    ))
        except IOError:
            raise CommandError("Error writing to file: %s" % output_filename)
开发者ID:PaoloC68,项目名称:edx-platform,代码行数:36,代码来源:anonymized_id_mapping.py

示例12: handle

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
    def handle(self, *args, **options):
        """Handler for command."""

        task_number = options['task_number']

        if len(args) == 2:
            course_id = SlashSeparatedCourseKey.from_deprecated_string(args[0])
            usage_key = course_id.make_usage_key_from_deprecated_string(args[1])
        else:
            print self.help
            return

        try:
            course = get_course(course_id)
        except ValueError as err:
            print err
            return

        descriptor = modulestore().get_item(usage_key, depth=0)
        if descriptor is None:
            print "Location {0} not found in course".format(usage_key)
            return

        try:
            enrolled_students = CourseEnrollment.users_enrolled_in(course_id)
            print "Total students enrolled in {0}: {1}".format(course_id, enrolled_students.count())

            calculate_task_statistics(enrolled_students, course, usage_key, task_number)

        except KeyboardInterrupt:
            print "\nOperation Cancelled"
开发者ID:aemilcar,项目名称:edx-platform,代码行数:33,代码来源:openended_stats.py

示例13: section_problem_grade_distrib

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
def section_problem_grade_distrib(request, course_id, section):
    """
    Creates a json with the grade distribution for the problems in the specified section.

    `request` django request

    `course_id` the course ID for the course interested in

    `section` The zero-based index of the section for the course

    Returns the format in dashboard_data.get_d3_section_grade_distrib

    If this is requested multiple times quickly for the same course, it is better to call all_problem_grade_distribution
    and pick out the sections of interest.
    """
    json = {}

    # Only instructor for this particular course can request this information
    course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    if has_instructor_access_for_class(request.user, course_key):
        try:
            json = dashboard_data.get_d3_section_grade_distrib(course_key, section)
        except Exception as ex:  # pylint: disable=broad-except
            log.error('Generating metrics failed with exception: %s', ex)
            json = {'error': "error"}
    else:
        json = {'error': "Access Denied: User does not have access to this course's data"}

    return HttpResponse(simplejson.dumps(json), mimetype="application/json")
开发者ID:bmcdonald2,项目名称:edx-platform,代码行数:31,代码来源:views.py

示例14: all_sequential_open_distrib

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
def all_sequential_open_distrib(request, course_id):
    """
    Creates a json with the open distribution for all the subsections in the course.

    `request` django request

    `course_id` the course ID for the course interested in

    Returns the format in dashboard_data.get_d3_sequential_open_distrib
    """

    json = {}

    # Only instructor for this particular course can request this information
    course_key = SlashSeparatedCourseKey.from_deprecated_string(course_id)
    if has_instructor_access_for_class(request.user, course_key):
        try:
            json = dashboard_data.get_d3_sequential_open_distrib(course_key)
        except Exception as ex:  # pylint: disable=broad-except
            log.error('Generating metrics failed with exception: %s', ex)
            json = {'error': "error"}
    else:
        json = {'error': "Access Denied: User does not have access to this course's data"}

    return HttpResponse(simplejson.dumps(json), mimetype="application/json")
开发者ID:bmcdonald2,项目名称:edx-platform,代码行数:27,代码来源:views.py

示例15: initdb

# 需要导入模块: from xmodule.modulestore.locations import SlashSeparatedCourseKey [as 别名]
# 或者: from xmodule.modulestore.locations.SlashSeparatedCourseKey import from_deprecated_string [as 别名]
    def initdb(self, default):
        """
        Initialize the database and create one test course in it
        """
        # set the default modulestore
        self.options['stores']['default'] = self.options['stores'][default]
        self.store = MixedModuleStore(**self.options)
        self.addCleanup(self.store.close_all_connections)

        # convert to CourseKeys
        self.course_locations = {
            course_id: SlashSeparatedCourseKey.from_deprecated_string(course_id)
            for course_id in [self.MONGO_COURSEID, self.XML_COURSEID1, self.XML_COURSEID2]
        }
        # and then to the root UsageKey
        self.course_locations = {
            course_id: course_key.make_usage_key('course', course_key.run)
            for course_id, course_key in self.course_locations.iteritems()  # pylint: disable=maybe-no-member
        }
        self.fake_location = Location('foo', 'bar', 'slowly', 'vertical', 'baz')
        self.import_chapter_location = self.course_locations[self.MONGO_COURSEID].replace(
            category='chapter', name='Overview'
        )
        self.xml_chapter_location = self.course_locations[self.XML_COURSEID1].replace(
            category='chapter', name='Overview'
        )
        # get Locators and set up the loc mapper if app is Locator based
        if default == 'split':
            self.fake_location = loc_mapper().translate_location(self.fake_location)

        self._create_course(default, self.course_locations[self.MONGO_COURSEID].course_key)
开发者ID:PaoloC68,项目名称:edx-platform,代码行数:33,代码来源:test_mixed_modulestore.py


注:本文中的xmodule.modulestore.locations.SlashSeparatedCourseKey.from_deprecated_string方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。