本文整理汇总了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)
示例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
示例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)))
示例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)
示例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)
示例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
示例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
示例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()
示例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.
示例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()
示例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
示例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)
示例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)
示例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)
示例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")