本文整理汇总了Python中xmodule.modulestore.Location.parse_course_id方法的典型用法代码示例。如果您正苦于以下问题:Python Location.parse_course_id方法的具体用法?Python Location.parse_course_id怎么用?Python Location.parse_course_id使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xmodule.modulestore.Location
的用法示例。
在下文中一共展示了Location.parse_course_id方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _infer_course_id_try
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def _infer_course_id_try(self, location):
"""
Create, Update, Delete operations don't require a fully-specified course_id, but
there's no complete & sound general way to compute the course_id except via the
proper modulestore. This method attempts several sound but not complete methods.
:param location: an old style Location
"""
if isinstance(location, CourseLocator):
return location.package_id
elif isinstance(location, basestring):
try:
location = Location(location)
except InvalidLocationError:
# try to parse as a course_id
try:
Location.parse_course_id(location)
# it's already a course_id
return location
except ValueError:
# cannot interpret the location
return None
# location is a Location at this point
if location.category == 'course': # easiest case
return location.course_id
# try finding in loc_mapper
try:
# see if the loc mapper knows the course id (requires double translation)
locator = loc_mapper().translate_location_to_course_locator(None, location)
location = loc_mapper().translate_locator_to_location(locator, get_course=True)
return location.course_id
except ItemNotFoundError:
pass
# expensive query against all location-based modulestores to look for location.
for store in self.modulestores.itervalues():
if isinstance(location, store.reference_type):
try:
xblock = store.get_item(location)
course_id = self._get_course_id_from_block(xblock, store)
if course_id is not None:
return course_id
except NotImplementedError:
blocks = store.get_items(location)
if len(blocks) == 1:
block = blocks[0]
try:
return block.course_id
except UndefinedContext:
pass
except ItemNotFoundError:
pass
# if we get here, it must be in a Locator based store, but we won't be able to find
# it.
return None
示例2: test_parse_course_id
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def test_parse_course_id(self):
"""
Test the parse_course_id class method
"""
source_string = "myorg/mycourse/myrun"
parsed = Location.parse_course_id(source_string)
self.assertEqual(parsed["org"], "myorg")
self.assertEqual(parsed["course"], "mycourse")
self.assertEqual(parsed["name"], "myrun")
with self.assertRaises(ValueError):
Location.parse_course_id("notlegit.id/foo")
示例3: create_course
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def create_course(self, course_id, user_id=None, store_name='default', **kwargs):
"""
Creates and returns the course.
:param org: the org
:param fields: a dict of xblock field name - value pairs for the course module.
:param metadata: the old way of setting fields by knowing which ones are scope.settings v scope.content
:param definition_data: the complement to metadata which is also a subset of fields
:returns: course xblock
"""
store = self.modulestores[store_name]
if not hasattr(store, 'create_course'):
raise NotImplementedError(u"Cannot create a course on store %s" % store_name)
if store.get_modulestore_type(course_id) == SPLIT_MONGO_MODULESTORE_TYPE:
try:
course_dict = Location.parse_course_id(course_id)
org = course_dict['org']
course_id = "{org}.{course}.{name}".format(**course_dict)
except ValueError:
org = None
org = kwargs.pop('org', org)
fields = kwargs.pop('fields', {})
fields.update(kwargs.pop('metadata', {}))
fields.update(kwargs.pop('definition_data', {}))
course = store.create_course(course_id, org, user_id, fields=fields, **kwargs)
else: # assume mongo
course = store.create_course(course_id, **kwargs)
return course
示例4: handle
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def handle(self, *args, **options):
"Execute the command"
if len(args) != 2:
raise CommandError("clone requires 2 arguments: <source-course_id> <dest-course_id>")
source_course_id = args[0]
dest_course_id = args[1]
mstore = modulestore('direct')
cstore = contentstore()
course_id_dict = Location.parse_course_id(dest_course_id)
mstore.ignore_write_events_on_courses.append('{org}/{course}'.format(**course_id_dict))
print("Cloning course {0} to {1}".format(source_course_id, dest_course_id))
source_location = CourseDescriptor.id_to_location(source_course_id)
dest_location = CourseDescriptor.id_to_location(dest_course_id)
if clone_course(mstore, cstore, source_location, dest_location):
# be sure to recompute metadata inheritance after all those updates
mstore.refresh_cached_metadata_inheritance_tree(dest_location)
print("copying User permissions...")
# purposely avoids auth.add_user b/c it doesn't have a caller to authorize
CourseInstructorRole(dest_location).add_users(
*CourseInstructorRole(source_location).users_with_role()
)
CourseStaffRole(dest_location).add_users(
*CourseStaffRole(source_location).users_with_role()
)
示例5: delete_course_and_groups
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def delete_course_and_groups(course_id, commit=False):
"""
This deletes the courseware associated with a course_id as well as cleaning update_item
the various user table stuff (groups, permissions, etc.)
"""
module_store = modulestore('direct')
content_store = contentstore()
course_id_dict = Location.parse_course_id(course_id)
module_store.ignore_write_events_on_courses.append('{org}/{course}'.format(**course_id_dict))
loc = CourseDescriptor.id_to_location(course_id)
if delete_course(module_store, content_store, loc, commit):
print 'removing User permissions from course....'
# in the django layer, we need to remove all the user permissions groups associated with this course
if commit:
try:
staff_role = CourseStaffRole(loc)
staff_role.remove_users(*staff_role.users_with_role())
instructor_role = CourseInstructorRole(loc)
instructor_role.remove_users(*instructor_role.users_with_role())
except Exception as err:
log.error("Error in deleting course groups for {0}: {1}".format(loc, err))
# remove location of this course from loc_mapper and cache
loc_mapper().delete_course_mapping(loc)
示例6: handle_grade_event
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def handle_grade_event(block, event_type, event):
user_id = event.get('user_id', user.id)
# Construct the key for the module
key = KeyValueStore.Key(
scope=Scope.user_state,
user_id=user_id,
block_scope_id=descriptor.location,
field_name='grade'
)
student_module = field_data_cache.find_or_create(key)
# Update the grades
student_module.grade = event.get('value')
student_module.max_grade = event.get('max_value')
# Save all changes to the underlying KeyValueStore
student_module.save()
# Bin score into range and increment stats
score_bucket = get_score_bucket(student_module.grade, student_module.max_grade)
course_id_dict = Location.parse_course_id(course_id)
tags = [
u"org:{org}".format(**course_id_dict),
u"course:{course}".format(**course_id_dict),
u"run:{name}".format(**course_id_dict),
u"score_bucket:{0}".format(score_bucket)
]
if grade_bucket_type is not None:
tags.append('type:%s' % grade_bucket_type)
dog_stats_api.increment("lms.courseware.question_answered", tags=tags)
示例7: _section_course_info
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def _section_course_info(course_id, access):
""" Provide data for the corresponding dashboard section """
course = get_course_by_id(course_id, depth=None)
course_id_dict = Location.parse_course_id(course_id)
section_data = {
'section_key': 'course_info',
'section_display_name': _('Course Info'),
'access': access,
'course_id': course_id,
'course_org': course_id_dict['org'],
'course_num': course_id_dict['course'],
'course_name': course_id_dict['name'],
'course_display_name': course.display_name,
'enrollment_count': CourseEnrollment.num_enrolled_in(course_id),
'has_started': course.has_started(),
'has_ended': course.has_ended(),
'list_instructor_tasks_url': reverse('list_instructor_tasks', kwargs={'course_id': course_id}),
}
try:
advance = lambda memo, (letter, score): "{}: {}, ".format(letter, score) + memo
section_data['grade_cutoffs'] = reduce(advance, course.grade_cutoffs.items(), "")[:-2]
except Exception:
section_data['grade_cutoffs'] = "Not Available"
# section_data['offline_grades'] = offline_grades_available(course_id)
try:
section_data['course_errors'] = [(escape(a), '') for (a, _unused) in modulestore().get_item_errors(course.location)]
except Exception:
section_data['course_errors'] = [('Error fetching errors', '')]
return section_data
示例8: create_item
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def create_item(self, course_or_parent_loc, category, user_id=None, **kwargs):
"""
Create and return the item. If parent_loc is a specific location v a course id,
it installs the new item as a child of the parent (if the parent_loc is a specific
xblock reference).
:param course_or_parent_loc: Can be a course_id (org/course/run), CourseLocator,
Location, or BlockUsageLocator but must be what the persistence modulestore expects
"""
# find the store for the course
course_id = self._infer_course_id_try(course_or_parent_loc)
if course_id is None:
raise ItemNotFoundError(u"Cannot find modulestore for %s" % course_or_parent_loc)
store = self._get_modulestore_for_courseid(course_id)
location = kwargs.pop('location', None)
# invoke its create_item
if isinstance(store, MongoModuleStore):
block_id = kwargs.pop('block_id', getattr(location, 'name', uuid4().hex))
# convert parent loc if it's legit
if isinstance(course_or_parent_loc, basestring):
parent_loc = None
if location is None:
loc_dict = Location.parse_course_id(course_id)
loc_dict['name'] = block_id
location = Location(category=category, **loc_dict)
else:
parent_loc = course_or_parent_loc
# must have a legitimate location, compute if appropriate
if location is None:
location = parent_loc.replace(category=category, name=block_id)
# do the actual creation
xblock = store.create_and_save_xmodule(location, **kwargs)
# don't forget to attach to parent
if parent_loc is not None and not 'detached' in xblock._class_tags:
parent = store.get_item(parent_loc)
parent.children.append(location.url())
store.update_item(parent)
elif isinstance(store, SplitMongoModuleStore):
if isinstance(course_or_parent_loc, basestring): # course_id
course_or_parent_loc = loc_mapper().translate_location_to_course_locator(
# hardcode draft version until we figure out how we're handling branches from app
course_or_parent_loc, None, published=False
)
elif not isinstance(course_or_parent_loc, CourseLocator):
raise ValueError(u"Cannot create a child of {} in split. Wrong repr.".format(course_or_parent_loc))
# split handles all the fields in one dict not separated by scope
fields = kwargs.get('fields', {})
fields.update(kwargs.pop('metadata', {}))
fields.update(kwargs.pop('definition_data', {}))
kwargs['fields'] = fields
xblock = store.create_item(course_or_parent_loc, category, user_id, **kwargs)
else:
raise NotImplementedError(u"Cannot create an item on store %s" % store)
return xblock
示例9: id_to_location
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def id_to_location(course_id):
'''Convert the given course_id (org/course/name) to a location object.
Throws ValueError if course_id is of the wrong format.
'''
course_id_dict = Location.parse_course_id(course_id)
course_id_dict['tag'] = 'i4x'
course_id_dict['category'] = 'course'
return Location(course_id_dict)
示例10: generate_location
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def generate_location(course_id):
"""
Generate the locations for the given ids
"""
course_dict = Location.parse_course_id(course_id)
course_dict['tag'] = 'i4x'
course_dict['category'] = 'course'
return Location(course_dict)
示例11: get_course
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def get_course(self, course_id):
"""
Get the course with the given courseid (org/course/run)
"""
id_components = Location.parse_course_id(course_id)
id_components['tag'] = 'i4x'
id_components['category'] = 'course'
try:
return self.get_item(Location(id_components))
except ItemNotFoundError:
return None
示例12: create_course
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def create_course(self, course_id, definition_data=None, metadata=None, runtime=None):
"""
Create a course with the given course_id.
"""
if isinstance(course_id, Location):
location = course_id
if location.category != 'course':
raise ValueError(u"Course roots must be of category 'course': {}".format(unicode(location)))
else:
course_dict = Location.parse_course_id(course_id)
course_dict['category'] = 'course'
course_dict['tag'] = 'i4x'
location = Location(course_dict)
return self.create_and_save_xmodule(location, definition_data, metadata, runtime)
示例13: convert_legacy_static_url_with_course_id
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def convert_legacy_static_url_with_course_id(path, course_id):
"""
Returns a path to a piece of static content when we are provided with a filepath and
a course_id
"""
# Generate url of urlparse.path component
scheme, netloc, orig_path, params, query, fragment = urlparse(path)
course_id_dict = Location.parse_course_id(course_id)
loc = StaticContent.compute_location(course_id_dict['org'], course_id_dict['course'], orig_path)
loc_url = StaticContent.get_url_path_from_location(loc)
# Reconstruct with new path
return urlunparse((scheme, netloc, loc_url, params, query, fragment))
示例14: update_enrollment
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def update_enrollment(self, mode=None, is_active=None):
"""
Updates an enrollment for a user in a class. This includes options
like changing the mode, toggling is_active True/False, etc.
Also emits relevant events for analytics purposes.
This saves immediately.
"""
activation_changed = False
# if is_active is None, then the call to update_enrollment didn't specify
# any value, so just leave is_active as it is
if self.is_active != is_active and is_active is not None:
self.is_active = is_active
activation_changed = True
mode_changed = False
# if mode is None, the call to update_enrollment didn't specify a new
# mode, so leave as-is
if self.mode != mode and mode is not None:
self.mode = mode
mode_changed = True
if activation_changed or mode_changed:
self.save()
if activation_changed:
course_id_dict = Location.parse_course_id(self.course_id)
if self.is_active:
self.emit_event(EVENT_NAME_ENROLLMENT_ACTIVATED)
dog_stats_api.increment(
"common.student.enrollment",
tags=[u"org:{org}".format(**course_id_dict),
u"course:{course}".format(**course_id_dict),
u"run:{name}".format(**course_id_dict),
u"mode:{}".format(self.mode)]
)
else:
unenroll_done.send(sender=None, course_enrollment=self)
self.emit_event(EVENT_NAME_ENROLLMENT_DEACTIVATED)
dog_stats_api.increment(
"common.student.unenrollment",
tags=[u"org:{org}".format(**course_id_dict),
u"course:{course}".format(**course_id_dict),
u"run:{name}".format(**course_id_dict),
u"mode:{}".format(self.mode)]
)
示例15: test_course_name_only
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import parse_course_id [as 别名]
def test_course_name_only(self):
# Munge course id - common
bad_id = Location.parse_course_id(self.course.id)['name']
form_data = {'course_id': bad_id, 'email_enabled': True}
form = CourseAuthorizationAdminForm(data=form_data)
# Validation shouldn't work
self.assertFalse(form.is_valid())
error_msg = form._errors['course_id'][0]
self.assertIn(u'--- Entered course id was: "{0}". '.format(bad_id), error_msg)
self.assertIn(u'Please recheck that you have supplied a course id in the format: ORG/COURSE/RUN', error_msg)
with self.assertRaisesRegexp(ValueError, "The CourseAuthorization could not be created because the data didn't validate."):
form.save()