本文整理汇总了Python中xmodule.modulestore.Location.replace方法的典型用法代码示例。如果您正苦于以下问题:Python Location.replace方法的具体用法?Python Location.replace怎么用?Python Location.replace使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xmodule.modulestore.Location
的用法示例。
在下文中一共展示了Location.replace方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _construct
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def _construct(cls, system, contents, error_msg, location):
if isinstance(location, dict) and 'course' in location:
location = Location(location)
if isinstance(location, Location) and location.name is None:
location = location.replace(
category='error',
# Pick a unique url_name -- the sha1 hash of the contents.
# NOTE: We could try to pull out the url_name of the errored descriptor,
# but url_names aren't guaranteed to be unique between descriptor types,
# and ErrorDescriptor can wrap any type. When the wrapped module is fixed,
# it will be written out with the original url_name.
name=hashlib.sha1(contents.encode('utf8')).hexdigest()
)
# real metadata stays in the content, but add a display name
model_data = {
'error_msg': str(error_msg),
'contents': contents,
'display_name': 'Error: ' + location.url(),
'location': location,
'category': 'error'
}
return cls(
system,
model_data,
)
示例2: create_item
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def create_item(request):
parent_location = Location(request.POST["parent_location"])
category = request.POST["category"]
display_name = request.POST.get("display_name")
if not has_access(request.user, parent_location):
raise PermissionDenied()
parent = get_modulestore(category).get_item(parent_location)
dest_location = parent_location.replace(category=category, name=uuid4().hex)
# get the metadata, display_name, and definition from the request
metadata = {}
data = None
template_id = request.POST.get("boilerplate")
if template_id is not None:
clz = XModuleDescriptor.load_class(category)
if clz is not None:
template = clz.get_template(template_id)
if template is not None:
metadata = template.get("metadata", {})
data = template.get("data")
if display_name is not None:
metadata["display_name"] = display_name
get_modulestore(category).create_and_save_xmodule(
dest_location, definition_data=data, metadata=metadata, system=parent.system
)
if category not in DETACHED_CATEGORIES:
get_modulestore(parent.location).update_children(parent_location, parent.children + [dest_location.url()])
return JsonResponse({"id": dest_location.url()})
示例3: _construct
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def _construct(cls, system, contents, error_msg, location):
location = Location(location)
if error_msg is None:
# this string is not marked for translation because we don't have
# access to the user context, and this will only be seen by staff
error_msg = 'Error not available'
if location.category == 'error':
location = location.replace(
# Pick a unique url_name -- the sha1 hash of the contents.
# NOTE: We could try to pull out the url_name of the errored descriptor,
# but url_names aren't guaranteed to be unique between descriptor types,
# and ErrorDescriptor can wrap any type. When the wrapped module is fixed,
# it will be written out with the original url_name.
name=hashlib.sha1(contents.encode('utf8')).hexdigest()
)
# real metadata stays in the content, but add a display name
field_data = DictFieldData({
'error_msg': str(error_msg),
'contents': contents,
'location': location,
'category': 'error'
})
return system.construct_xblock_from_class(
cls,
# The error module doesn't use scoped data, and thus doesn't need
# real scope keys
ScopeIds('error', None, location, location),
field_data,
)
示例4: _import_module
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def _import_module(module):
module.location = module.location.replace(revision='draft')
# make sure our parent has us in its list of children
# this is to make sure private only verticals show up
# in the list of children since they would have been
# filtered out from the non-draft store export
if module.location.category == 'vertical':
non_draft_location = module.location.replace(revision=None)
sequential_url = module.xml_attributes['parent_sequential_url']
index = int(module.xml_attributes['index_in_children_list'])
seq_location = Location(sequential_url)
# IMPORTANT: Be sure to update the sequential
# in the NEW namespace
seq_location = seq_location.replace(
org=target_location_namespace.org,
course=target_location_namespace.course
)
sequential = store.get_item(seq_location, depth=0)
if non_draft_location.url() not in sequential.children:
sequential.children.insert(index, non_draft_location.url())
store.update_item(sequential, '**replace_user**')
import_module(
module, draft_store, course_data_path,
static_content_store, source_location_namespace,
target_location_namespace, allow_not_found=True
)
for child in module.get_children():
_import_module(child)
示例5: _construct
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def _construct(cls, system, contents, error_msg, location):
if isinstance(location, dict) and 'course' in location:
location = Location(location)
if isinstance(location, Location) and location.name is None:
location = location.replace(
category='error',
# Pick a unique url_name -- the sha1 hash of the contents.
# NOTE: We could try to pull out the url_name of the errored descriptor,
# but url_names aren't guaranteed to be unique between descriptor types,
# and ErrorDescriptor can wrap any type. When the wrapped module is fixed,
# it will be written out with the original url_name.
name=hashlib.sha1(contents.encode('utf8')).hexdigest()
)
# real metadata stays in the content, but add a display name
field_data = DictFieldData({
'error_msg': str(error_msg),
'contents': contents,
'display_name': 'Error: ' + location.url(),
'location': location,
'category': 'error'
})
return system.construct_xblock_from_class(
cls,
field_data,
# The error module doesn't use scoped data, and thus doesn't need
# real scope keys
ScopeIds('error', None, location, location)
)
示例6: _query_children_for_cache_children
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def _query_children_for_cache_children(self, items):
# first get non-draft in a round-trip
to_process_non_drafts = super(DraftModuleStore, self)._query_children_for_cache_children(items)
to_process_dict = {}
for non_draft in to_process_non_drafts:
to_process_dict[Location(non_draft["_id"])] = non_draft
# now query all draft content in another round-trip
query = {
'_id': {'$in': [namedtuple_to_son(as_draft(Location(item))) for item in items]}
}
to_process_drafts = list(self.collection.find(query))
# now we have to go through all drafts and replace the non-draft
# with the draft. This is because the semantics of the DraftStore is to
# always return the draft - if available
for draft in to_process_drafts:
draft_loc = Location(draft["_id"])
draft_as_non_draft_loc = draft_loc.replace(revision=None)
# does non-draft exist in the collection
# if so, replace it
if draft_as_non_draft_loc in to_process_dict:
to_process_dict[draft_as_non_draft_loc] = draft
# convert the dict - which is used for look ups - back into a list
queried_children = to_process_dict.values()
return queried_children
示例7: test_post_course_update
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def test_post_course_update(self):
"""
Test that a user can successfully post on course updates and handouts of a course
whose location in not in loc_mapper
"""
# create a course via the view handler
course_location = Location(['i4x', 'Org_1', 'Course_1', 'course', 'Run_1'])
course_locator = loc_mapper().translate_location(
course_location.course_id, course_location, False, True
)
self.client.ajax_post(
course_locator.url_reverse('course'),
{
'org': course_location.org,
'number': course_location.course,
'display_name': 'test course',
'run': course_location.name,
}
)
branch = u'draft'
version = None
block = u'updates'
updates_locator = BlockUsageLocator(
package_id=course_location.course_id.replace('/', '.'), branch=branch, version_guid=version, block_id=block
)
content = u"Sample update"
payload = {'content': content, 'date': 'January 8, 2013'}
course_update_url = updates_locator.url_reverse('course_info_update')
resp = self.client.ajax_post(course_update_url, payload)
# check that response status is 200 not 400
self.assertEqual(resp.status_code, 200)
payload = json.loads(resp.content)
self.assertHTMLEqual(payload['content'], content)
# now test that calling translate_location returns a locator whose block_id is 'updates'
updates_location = course_location.replace(category='course_info', name=block)
updates_locator = loc_mapper().translate_location(course_location.course_id, updates_location)
self.assertTrue(isinstance(updates_locator, BlockUsageLocator))
self.assertEqual(updates_locator.block_id, block)
# check posting on handouts
block = u'handouts'
handouts_locator = BlockUsageLocator(
package_id=updates_locator.package_id, branch=updates_locator.branch, version_guid=version, block_id=block
)
course_handouts_url = handouts_locator.url_reverse('xblock')
content = u"Sample handout"
payload = {"data": content}
resp = self.client.ajax_post(course_handouts_url, payload)
# check that response status is 200 not 500
self.assertEqual(resp.status_code, 200)
payload = json.loads(resp.content)
self.assertHTMLEqual(payload['data'], content)
示例8: create_new_course
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def create_new_course(request):
"""
Create a new course
"""
if not is_user_in_creator_group(request.user):
raise PermissionDenied()
org = request.POST.get("org")
number = request.POST.get("number")
display_name = request.POST.get("display_name")
try:
dest_location = Location("i4x", org, number, "course", Location.clean(display_name))
except InvalidLocationError as error:
return JsonResponse(
{"ErrMsg": "Unable to create course '{name}'.\n\n{err}".format(name=display_name, err=error.message)}
)
# see if the course already exists
existing_course = None
try:
existing_course = modulestore("direct").get_item(dest_location)
except ItemNotFoundError:
pass
if existing_course is not None:
return JsonResponse({"ErrMsg": "There is already a course defined with this name."})
course_search_location = ["i4x", dest_location.org, dest_location.course, "course", None]
courses = modulestore().get_items(course_search_location)
if len(courses) > 0:
return JsonResponse(
{"ErrMsg": "There is already a course defined with the same organization and course number."}
)
# instantiate the CourseDescriptor and then persist it
# note: no system to pass
if display_name is None:
metadata = {}
else:
metadata = {"display_name": display_name}
modulestore("direct").create_and_save_xmodule(dest_location, metadata=metadata)
new_course = modulestore("direct").get_item(dest_location)
# clone a default 'about' overview module as well
dest_about_location = dest_location.replace(category="about", name="overview")
overview_template = AboutDescriptor.get_template("overview.yaml")
modulestore("direct").create_and_save_xmodule(
dest_about_location, system=new_course.system, definition_data=overview_template.get("data")
)
initialize_course_tabs(new_course)
create_all_course_groups(request.user, new_course.location)
# seed the forums
seed_permissions_roles(new_course.location.course_id)
return JsonResponse({"id": new_course.location.url()})
示例9: test_name_collision
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def test_name_collision(self):
"""
Test dwim translation when the old name was not unique
"""
org = "myorg"
course = "another_course"
name = "running_again"
course_location = Location('i4x', org, course, 'course', name)
course_xlate = loc_mapper().translate_location(None, course_location, add_entry_if_missing=True)
self.assertEqual(course_location, loc_mapper().translate_locator_to_location(course_xlate))
eponymous_block = course_location.replace(category='chapter')
chapter_xlate = loc_mapper().translate_location(None, eponymous_block, add_entry_if_missing=True)
self.assertEqual(course_location, loc_mapper().translate_locator_to_location(course_xlate))
self.assertEqual(eponymous_block, loc_mapper().translate_locator_to_location(chapter_xlate))
# and a non-existent one w/o add
eponymous_block = course_location.replace(category='problem')
with self.assertRaises(ItemNotFoundError):
chapter_xlate = loc_mapper().translate_location(None, eponymous_block, add_entry_if_missing=False)
示例10: load_item
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def load_item(self, location):
"""
Return an XModule instance for the specified location
"""
location = Location(location)
json_data = self.module_data.get(location)
if json_data is None:
module = self.modulestore.get_item(location)
if module is not None:
# update our own cache after going to the DB to get cache miss
self.module_data.update(module.runtime.module_data)
return module
else:
# load the module and apply the inherited metadata
try:
category = json_data['location']['category']
class_ = XModuleDescriptor.load_class(
category,
self.default_class
)
definition = json_data.get('definition', {})
metadata = json_data.get('metadata', {})
for old_name, new_name in getattr(class_, 'metadata_translations', {}).items():
if old_name in metadata:
metadata[new_name] = metadata[old_name]
del metadata[old_name]
kvs = MongoKeyValueStore(
definition.get('data', {}),
definition.get('children', []),
metadata,
)
field_data = DbModel(kvs)
scope_ids = ScopeIds(None, category, location, location)
module = self.construct_xblock_from_class(class_, field_data, scope_ids)
if self.cached_metadata is not None:
# parent container pointers don't differentiate between draft and non-draft
# so when we do the lookup, we should do so with a non-draft location
non_draft_loc = location.replace(revision=None)
# Convert the serialized fields values in self.cached_metadata
# to python values
metadata_to_inherit = self.cached_metadata.get(non_draft_loc.url(), {})
inherit_metadata(module, metadata_to_inherit)
# decache any computed pending field settings
module.save()
return module
except:
log.warning("Failed to load descriptor", exc_info=True)
return ErrorDescriptor.from_json(
json_data,
self,
json_data['location'],
error_msg=exc_info_to_str(sys.exc_info())
)
示例11: load_item
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def load_item(self, location):
"""
Return an XModule instance for the specified location
"""
location = Location(location)
json_data = self.module_data.get(location)
if json_data is None:
module = self.modulestore.get_item(location)
if module is not None:
# update our own cache after going to the DB to get cache miss
self.module_data.update(module.system.module_data)
return module
else:
# load the module and apply the inherited metadata
try:
category = json_data['location']['category']
class_ = XModuleDescriptor.load_class(
category,
self.default_class
)
definition = json_data.get('definition', {})
metadata = json_data.get('metadata', {})
for old_name, new_name in class_.metadata_translations.items():
if old_name in metadata:
metadata[new_name] = metadata[old_name]
del metadata[old_name]
kvs = MongoKeyValueStore(
definition.get('data', {}),
definition.get('children', []),
metadata,
location,
category
)
model_data = DbModel(kvs, class_, None, MongoUsage(self.course_id, location))
model_data['category'] = category
model_data['location'] = location
module = class_(self, model_data)
if self.cached_metadata is not None:
# parent container pointers don't differentiate between draft and non-draft
# so when we do the lookup, we should do so with a non-draft location
non_draft_loc = location.replace(revision=None)
metadata_to_inherit = self.cached_metadata.get(non_draft_loc.url(), {})
inherit_metadata(module, metadata_to_inherit)
return module
except:
log.warning("Failed to load descriptor", exc_info=True)
return ErrorDescriptor.from_json(
json_data,
self,
json_data['location'],
error_msg=exc_info_to_str(sys.exc_info())
)
示例12: fetch
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def fetch(cls, course_location):
"""
Fetch the course details for the given course from persistence and return a CourseDetails model.
"""
if not isinstance(course_location, Location):
course_location = Location(course_location)
course = cls(course_location)
descriptor = get_modulestore(course_location).get_item(course_location)
course.start_date = descriptor.start
course.end_date = descriptor.end
course.enrollment_start = descriptor.enrollment_start
course.enrollment_end = descriptor.enrollment_end
course.course_image_name = descriptor.course_image
course.course_image_asset_path = course_image_url(descriptor)
temploc = course_location.replace(category='about', name='syllabus')
try:
course.syllabus = get_modulestore(temploc).get_item(temploc).data
except ItemNotFoundError:
pass
temploc = temploc.replace(name='overview')
try:
course.overview = get_modulestore(temploc).get_item(temploc).data
except ItemNotFoundError:
pass
temploc = temploc.replace(name='tags')
try:
course.tags = get_modulestore(temploc).get_item(temploc).data
except ItemNotFoundError:
pass
temploc = temploc.replace(name='effort')
try:
course.effort = get_modulestore(temploc).get_item(temploc).data
except ItemNotFoundError:
pass
temploc = temploc.replace(name='video')
try:
raw_video = get_modulestore(temploc).get_item(temploc).data
course.intro_video = CourseDetails.parse_video_tag(raw_video)
except ItemNotFoundError:
pass
return course
示例13: test_delete_block
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def test_delete_block(self):
"""
test delete_block_location_translator(location, old_course_id=None)
"""
org = 'foo_org'
course = 'bar_course'
new_style_course_id = '{}.geek_dept.{}.baz_run'.format(org, course)
loc_mapper().create_map_entry(
Location('i4x', org, course, 'course', 'baz_run'),
new_style_course_id,
block_map={
'abc123': {'problem': 'problem2'},
'48f23a10395384929234': {'chapter': 'chapter48f'},
'1': {'chapter': 'chapter1', 'problem': 'problem1'},
}
)
new_style_course_id2 = '{}.geek_dept.{}.delta_run'.format(org, course)
loc_mapper().create_map_entry(
Location('i4x', org, course, 'course', 'delta_run'),
new_style_course_id2,
block_map={
'abc123': {'problem': 'problem3'},
'48f23a10395384929234': {'chapter': 'chapter48b'},
'1': {'chapter': 'chapter2', 'problem': 'problem2'},
}
)
location = Location('i4x', org, course, 'problem', '1')
# delete from all courses
loc_mapper().delete_block_location_translator(location)
self.assertIsNone(loc_mapper().translate_locator_to_location(
BlockUsageLocator(course_id=new_style_course_id, usage_id='problem1')
))
self.assertIsNone(loc_mapper().translate_locator_to_location(
BlockUsageLocator(course_id=new_style_course_id2, usage_id='problem2')
))
# delete from one course
location = location.replace(name='abc123')
loc_mapper().delete_block_location_translator(location, '{}/{}/{}'.format(org, course, 'baz_run'))
with self.assertRaises(ItemNotFoundError):
loc_mapper().translate_location(
'{}/{}/{}'.format(org, course, 'baz_run'),
location,
add_entry_if_missing=False
)
locator = loc_mapper().translate_location(
'{}/{}/{}'.format(org, course, 'delta_run'),
location,
add_entry_if_missing=False
)
self.assertEqual(locator.usage_id, 'problem3')
示例14: convert_ref
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def convert_ref(reference):
"""
Convert a reference to the new namespace, but only
if the original namespace matched the original course.
Otherwise, returns the input value.
"""
new_ref = reference
ref = Location(reference)
in_original_namespace = (original_location.tag == ref.tag and
original_location.org == ref.org and
original_location.course == ref.course)
if in_original_namespace:
new_ref = ref.replace(
tag=target_location_namespace.tag,
org=target_location_namespace.org,
course=target_location_namespace.course
).url()
return new_ref
示例15: create_item
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import replace [as 别名]
def create_item(request):
"""View for create items."""
parent_location = Location(request.json['parent_location'])
category = request.json['category']
display_name = request.json.get('display_name')
if not has_access(request.user, parent_location):
raise PermissionDenied()
parent = get_modulestore(category).get_item(parent_location)
dest_location = parent_location.replace(category=category, name=uuid4().hex)
# get the metadata, display_name, and definition from the request
metadata = {}
data = None
template_id = request.json.get('boilerplate')
if template_id is not None:
clz = XModuleDescriptor.load_class(category)
if clz is not None:
template = clz.get_template(template_id)
if template is not None:
metadata = template.get('metadata', {})
data = template.get('data')
if display_name is not None:
metadata['display_name'] = display_name
get_modulestore(category).create_and_save_xmodule(
dest_location,
definition_data=data,
metadata=metadata,
system=parent.system,
)
if category not in DETACHED_CATEGORIES:
get_modulestore(parent.location).update_children(parent_location, parent.children + [dest_location.url()])
locator = loc_mapper().translate_location(
get_course_for_item(parent_location).location.course_id, dest_location, False, True
)
return JsonResponse({'id': dest_location.url(), "update_url": locator.url_reverse("xblock")})