當前位置: 首頁>>代碼示例>>Python>>正文


Python CourseKey.from_string方法代碼示例

本文整理匯總了Python中opaque_keys.edx.keys.CourseKey.from_string方法的典型用法代碼示例。如果您正苦於以下問題:Python CourseKey.from_string方法的具體用法?Python CourseKey.from_string怎麽用?Python CourseKey.from_string使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在opaque_keys.edx.keys.CourseKey的用法示例。


在下文中一共展示了CourseKey.from_string方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: filter_enrolled_in_course_id

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def filter_enrolled_in_course_id(self, queryset,
                                     name, value):  # pylint: disable=unused-argument
        '''

        This method converts the course id string to a CourseLocator object
        and returns the filtered queryset. This is required because
        CourseEnrollment course_id fields are of type CourseKeyField

        Query parameters with plus signs '+' in the string are automatically
        replaced with spaces, so we need to put the '+' back in for CourseKey
        to be able to create a course key object from the string
        '''
        course_key = CourseKey.from_string(value.replace(' ', '+'))
        enrollments = get_enrolled_in_exclude_admins(course_id=course_key)
        user_ids = enrollments.values_list('user__id', flat=True)
        return queryset.filter(id__in=user_ids) 
開發者ID:appsembler,項目名稱:figures,代碼行數:18,代碼來源:filters.py

示例2: site_course_helper

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def site_course_helper(self, pk):
        """Hep

        Improvements:
        * make this a decorator
        * Test this with both course id strings and CourseKey objects
        """
        course_id = pk.replace(' ', '+')
        try:
            course_key = CourseKey.from_string(course_id)
        except InvalidKeyError:
            raise NotFound()

        site = django.contrib.sites.shortcuts.get_current_site(self.request)
        if figures.helpers.is_multisite():
            if site != figures.sites.get_site_for_course(course_id):
                raise NotFound()
        else:
            get_object_or_404(CourseOverview,
                              pk=course_key)
        return site, course_id 
開發者ID:appsembler,項目名稱:figures,代碼行數:23,代碼來源:views.py

示例3: as_course_key

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def as_course_key(course_id):
    '''Returns course id as a CourseKey instance

    Convenience method to return the paramater unchanged if it is of type
    ``CourseKey`` or attempts to convert to ``CourseKey`` if of type str or
    unicode.

    Raises TypeError if an unsupported type is provided
    '''
    if isinstance(course_id, CourseKey):
        return course_id
    elif isinstance(course_id, basestring):  # noqa: F821
        return CourseKey.from_string(course_id)
    else:
        raise TypeError('Unable to convert course id with type "{}"'.format(
            type(course_id))) 
開發者ID:appsembler,項目名稱:figures,代碼行數:18,代碼來源:helpers.py

示例4: validate_user

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def validate_user(self, request, course_id):
        """Validate that course exists and user is enrolled in course"""
        try:
            course_key = CourseKey.from_string(course_id)
            c = CourseEnrollment.objects.get(user_id=request.user.id, course_id=course_key)
            if not c.is_active:
                msg = "Access Denied. {} is not currently enrolled in {}"\
                        .format(request.user.username, course_id)
                raise ValidationError(msg, 403)

        # Something wrong with CourseKey
        except InvalidKeyError as e:
            msg = "Course: {} not found".format(course_id)
            raise ValidationError(msg, 404)

        # Enrollment does not exist for user
        except CourseEnrollment.DoesNotExist:
            log.error("User: {} tried to access student notebook in: {}"\
                .format(request.user.username, course_id))
            msg = "Access Denied. Either course {} does not exist or user {} is not currently enrolled"\
                    .format(course_id, request.user.username)
            raise ValidationError(msg, 403) 
開發者ID:ibleducation,項目名稱:jupyter-edx-grader-xblock,代碼行數:24,代碼來源:views.py

示例5: get

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def get(self, request, course_id, unit_id, filename):
        """Serve autograded notebook as file download
        
        Denies access if instructor has not set `allow_graded_dl` to True
        """
        usage_key = UsageKey.from_string(unit_id)
        xblock = modulestore().get_item(usage_key)

        if xblock.allow_graded_dl:
            response = self.get_nb(request, FEEDBACK, course_id, unit_id, filename, 
                    ext=".html", username=request.user.username)
            response['Content-Disposition'] = 'attachment;'\
                'filename="{}_autograded.html"'.format(filename)
            return response
        else:
            msg = "Instructor has not enabled downloading of autograded notebooks"
            return HttpResponse(msg, status=403) 
開發者ID:ibleducation,項目名稱:jupyter-edx-grader-xblock,代碼行數:19,代碼來源:views.py

示例6: make_studio_data

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def make_studio_data(self, run, add_pacing=True, add_schedule=True, team=None):
        key = CourseKey.from_string(run.key)
        data = {
            'title': run.title,
            'org': key.org,
            'number': key.course,
            'run': key.run,
            'team': team or [],
        }
        if add_pacing:
            data['pacing_type'] = run.pacing_type
        if add_schedule:
            data['schedule'] = {
                'start': serialize_datetime(run.start),
                'end': serialize_datetime(run.end),
            }
        return data 
開發者ID:edx,項目名稱:course-discovery,代碼行數:19,代碼來源:test_utils.py

示例7: setUp

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def setUp(self):
        super().setUp()
        self.org = OrganizationFactory(name='MyOrg', key='myorg')
        self.course_run = CourseRunFactory(draft=True, title_override='MyCourse')
        self.course = self.course_run.course
        self.course.authoring_organizations.add(self.org)
        self.partner = self.course.partner
        self.group = GroupFactory()
        self.pc = self.make_user(email='pc@example.com')
        self.editor = self.make_user(groups=[self.group])
        self.editor2 = self.make_user(groups=[self.group])
        self.non_editor = self.make_user(groups=[self.group])
        self.legal = self.make_user(groups=[Group.objects.get(name=LEGAL_TEAM_GROUP_NAME)])

        CourseEditorFactory(user=self.editor, course=self.course)
        CourseEditorFactory(user=self.editor2, course=self.course)
        OrganizationExtensionFactory(group=self.group, organization=self.org)
        OrganizationUserRoleFactory(user=self.pc, organization=self.org, role=InternalUserRole.ProjectCoordinator)

        self.publisher_url = '{}courses/{}'.format(self.partner.publisher_url, self.course_run.course.uuid)
        self.studio_url = '{}course/{}'.format(self.partner.studio_url, self.course_run.key)
        self.admin_url = 'https://{}/admin/course_metadata/courserun/{}/change/'.format(
            self.partner.site.domain, self.course_run.id
        )
        self.run_num = CourseKey.from_string(self.course_run.key).run 
開發者ID:edx,項目名稱:course-discovery,代碼行數:27,代碼來源:test_emails.py

示例8: course_team_handler

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def course_team_handler(request, course_key_string=None, email=None):
    """
    The restful handler for course team users.

    GET
        html: return html page for managing course team
        json: return json representation of a particular course team member (email is required).
    POST or PUT
        json: modify the permissions for a particular course team member (email is required, as well as role in the payload).
    DELETE:
        json: remove a particular course team member from the course team (email is required).
    """
    course_key = CourseKey.from_string(course_key_string) if course_key_string else None
    if not has_course_access(request.user, course_key):
        raise PermissionDenied()

    if 'application/json' in request.META.get('HTTP_ACCEPT', 'application/json'):
        return _course_team_user(request, course_key, email)
    elif request.method == 'GET':  # assume html
        return _manage_users(request, course_key)
    else:
        return HttpResponseNotFound() 
開發者ID:jruiperezv,項目名稱:ANALYSE,代碼行數:24,代碼來源:user.py

示例9: get_tab_by_locator

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def get_tab_by_locator(tab_list, usage_key_string):
    """
    Look for a tab with the specified locator.  Returns the first matching tab.
    """
    tab_location = UsageKey.from_string(usage_key_string)
    item = modulestore().get_item(tab_location)
    static_tab = StaticTab(
        name=item.display_name,
        url_slug=item.location.name,
    )
    return CourseTabList.get_tab_by_id(tab_list, static_tab.tab_id)


# "primitive" tab edit functions driven by the command line.
# These should be replaced/deleted by a more capable GUI someday.
# Note that the command line UI identifies the tabs with 1-based
# indexing, but this implementation code is standard 0-based. 
開發者ID:jruiperezv,項目名稱:ANALYSE,代碼行數:19,代碼來源:tabs.py

示例10: orphan_handler

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def orphan_handler(request, course_key_string):
    """
    View for handling orphan related requests. GET gets all of the current orphans.
    DELETE removes all orphans (requires is_staff access)

    An orphan is a block whose category is not in the DETACHED_CATEGORY list, is not the root, and is not reachable
    from the root via children
    """
    course_usage_key = CourseKey.from_string(course_key_string)
    if request.method == 'GET':
        if has_course_access(request.user, course_usage_key):
            return JsonResponse([unicode(item) for item in modulestore().get_orphans(course_usage_key)])
        else:
            raise PermissionDenied()
    if request.method == 'DELETE':
        if request.user.is_staff:
            store = modulestore()
            items = store.get_orphans(course_usage_key)
            for itemloc in items:
                # need to delete all versions
                store.delete_item(itemloc, request.user.id, revision=ModuleStoreEnum.RevisionOption.all)
            return JsonResponse({'deleted': [unicode(item) for item in items]})
        else:
            raise PermissionDenied() 
開發者ID:jruiperezv,項目名稱:ANALYSE,代碼行數:26,代碼來源:item.py

示例11: course_info_handler

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def course_info_handler(request, course_key_string):
    """
    GET
        html: return html for editing the course info handouts and updates.
    """
    course_key = CourseKey.from_string(course_key_string)
    with modulestore().bulk_operations(course_key):
        course_module = _get_course_module(course_key, request.user)
        if 'text/html' in request.META.get('HTTP_ACCEPT', 'text/html'):
            return render_to_response(
                'course_info.html',
                {
                    'context_course': course_module,
                    'updates_url': reverse_course_url('course_info_update_handler', course_key),
                    'handouts_locator': course_key.make_usage_key('course_info', 'handouts'),
                    'base_asset_url': StaticContent.get_base_url_path_for_course_assets(course_module.id)
                }
            )
        else:
            return HttpResponseBadRequest("Only supports html requests")


# pylint: disable=unused-argument 
開發者ID:jruiperezv,項目名稱:ANALYSE,代碼行數:25,代碼來源:course.py

示例12: handle

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def handle(self, *args, **options):
        if len(args) != 1 and len(args) != 0:
            raise CommandError("empty_asset_trashcan requires one or no arguments: |<course_id>|")

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

            course_ids = [course_key]
        else:
            course_ids = [course.id for course in modulestore().get_courses()]

        if query_yes_no("Emptying trashcan. Confirm?", default="no"):
            empty_asset_trashcan(course_ids) 
開發者ID:jruiperezv,項目名稱:ANALYSE,代碼行數:18,代碼來源:empty_asset_trashcan.py

示例13: handle

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def handle(self, *args, **options):
        "Execute the command"
        if len(args) != 2:
            raise CommandError("export requires two arguments: <course id> <output path>")

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

        output_path = args[1]

        print("Exporting course id = {0} to {1}".format(course_key, output_path))

        root_dir = os.path.dirname(output_path)
        course_dir = os.path.splitext(os.path.basename(output_path))[0]

        export_to_xml(modulestore(), contentstore(), course_key, root_dir, course_dir) 
開發者ID:jruiperezv,項目名稱:ANALYSE,代碼行數:20,代碼來源:export.py

示例14: test_rerun

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def test_rerun(self):
        """
        Just testing the functionality the view handler adds over the tasks tested in test_clone_course
        """
        response = self.client.ajax_post('/course/', {
            'source_course_key': unicode(self.source_course_key),
            'org': self.source_course_key.org, 'course': self.source_course_key.course, 'run': 'copy',
            'display_name': 'not the same old name',
        })
        self.assertEqual(response.status_code, 200)
        data = parse_json(response)
        dest_course_key = CourseKey.from_string(data['destination_course_key'])

        self.assertEqual(dest_course_key.run, 'copy')
        dest_course = self.store.get_course(dest_course_key)
        self.assertEqual(dest_course.start, CourseFields.start.default) 
開發者ID:jruiperezv,項目名稱:ANALYSE,代碼行數:18,代碼來源:test_course_create_rerun.py

示例15: test_capa_module

# 需要導入模塊: from opaque_keys.edx.keys import CourseKey [as 別名]
# 或者: from opaque_keys.edx.keys.CourseKey import from_string [as 別名]
def test_capa_module(self):
        """Test that a problem treats markdown specially."""
        course = CourseFactory.create()

        problem_data = {
            'parent_locator': unicode(course.location),
            'category': 'problem'
        }

        resp = self.client.ajax_post(reverse_url('xblock_handler'), problem_data)
        self.assertEqual(resp.status_code, 200)
        payload = parse_json(resp)
        problem_loc = UsageKey.from_string(payload['locator'])
        problem = self.store.get_item(problem_loc)
        # should be a CapaDescriptor
        self.assertIsInstance(problem, CapaDescriptor, "New problem is not a CapaDescriptor")
        context = problem.get_context()
        self.assertIn('markdown', context, "markdown is missing from context")
        self.assertNotIn('markdown', problem.editable_metadata_fields, "Markdown slipped into the editable metadata fields") 
開發者ID:jruiperezv,項目名稱:ANALYSE,代碼行數:21,代碼來源:test_contentstore.py


注:本文中的opaque_keys.edx.keys.CourseKey.from_string方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。