本文整理汇总了Python中xmodule.modulestore.Location.url方法的典型用法代码示例。如果您正苦于以下问题:Python Location.url方法的具体用法?Python Location.url怎么用?Python Location.url使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xmodule.modulestore.Location
的用法示例。
在下文中一共展示了Location.url方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_old_location_helpers
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [as 别名]
def test_old_location_helpers(self):
"""
Test the functions intended to help with the conversion from old locations to locators
"""
location_tuple = ('i4x', 'mit', 'eecs.6002x', 'course', 't3_2013')
location = Location(location_tuple)
self.assertEqual(location, Locator.to_locator_or_location(location))
self.assertEqual(location, Locator.to_locator_or_location(location_tuple))
self.assertEqual(location, Locator.to_locator_or_location(list(location_tuple)))
self.assertEqual(location, Locator.to_locator_or_location(location.dict()))
locator = BlockUsageLocator(package_id='foo.bar', branch='alpha', block_id='deep')
self.assertEqual(locator, Locator.to_locator_or_location(locator))
self.assertEqual(locator.as_course_locator(), Locator.to_locator_or_location(locator.as_course_locator()))
self.assertEqual(location, Locator.to_locator_or_location(location.url()))
self.assertEqual(locator, Locator.to_locator_or_location(locator.url()))
self.assertEqual(locator, Locator.to_locator_or_location(locator.__dict__))
asset_location = Location(['c4x', 'mit', 'eecs.6002x', 'asset', 'selfie.jpeg'])
self.assertEqual(asset_location, Locator.to_locator_or_location(asset_location))
self.assertEqual(asset_location, Locator.to_locator_or_location(asset_location.url()))
def_location_url = "defx://version/" + '{:024x}'.format(random.randrange(16 ** 24))
self.assertEqual(DefinitionLocator(def_location_url), Locator.to_locator_or_location(def_location_url))
with self.assertRaises(ValueError):
Locator.to_locator_or_location(22)
with self.assertRaises(ValueError):
Locator.to_locator_or_location("hello.world.not.a.url")
self.assertIsNone(Locator.parse_url("unknown://foo.bar/baz"))
示例2: _construct
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [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)
)
示例3: _create_item
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [as 别名]
def _create_item(self, category, name, data, metadata, parent_category, parent_name, runtime):
"""
Create the item of the given category and block id in split and old mongo, add it to the optional
parent. The parent category is only needed because old mongo requires it for the id.
"""
location = Location('i4x', 'test_org', 'test_course', category, name)
self.old_mongo.create_and_save_xmodule(location, data, metadata, runtime)
if isinstance(data, basestring):
fields = {'data': data}
else:
fields = data.copy()
fields.update(metadata)
if parent_name:
# add child to parent in mongo
parent_location = Location('i4x', 'test_org', 'test_course', parent_category, parent_name)
parent = self.old_mongo.get_item(parent_location)
parent.children.append(location.url())
self.old_mongo.update_item(parent, self.userid)
# create pointer for split
course_or_parent_locator = BlockUsageLocator(
package_id=self.split_package_id,
branch='draft',
block_id=parent_name
)
else:
course_or_parent_locator = CourseLocator(
package_id='test_org.test_course.runid',
branch='draft',
)
self.split_mongo.create_item(course_or_parent_locator, category, self.userid, block_id=name, fields=fields)
示例4: _clone_modules
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [as 别名]
def _clone_modules(modulestore, modules, source_location, dest_location):
for module in modules:
original_loc = Location(module.location)
if original_loc.category != "course":
module.location = module.location._replace(
tag=dest_location.tag, org=dest_location.org, course=dest_location.course
)
else:
# on the course module we also have to update the module name
module.location = module.location._replace(
tag=dest_location.tag, org=dest_location.org, course=dest_location.course, name=dest_location.name
)
print "Cloning module {0} to {1}....".format(original_loc, module.location)
if "data" in module.fields and module.fields["data"].is_set_on(module) and isinstance(module.data, basestring):
module.data = rewrite_nonportable_content_links(
source_location.course_id, dest_location.course_id, module.data
)
# repoint children
if module.has_children:
new_children = []
for child_loc_url in module.children:
child_loc = Location(child_loc_url)
child_loc = child_loc._replace(
tag=dest_location.tag, org=dest_location.org, course=dest_location.course
)
new_children.append(child_loc.url())
module.children = new_children
modulestore.update_item(module, "**replace_user**")
示例5: delete_item
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [as 别名]
def delete_item(request):
item_location = request.POST['id']
item_location = Location(item_location)
# check permissions for this user within this course
if not has_access(request.user, item_location):
raise PermissionDenied()
# optional parameter to delete all children (default False)
delete_children = request.POST.get('delete_children', False)
delete_all_versions = request.POST.get('delete_all_versions', False)
store = get_modulestore(item_location)
item = store.get_item(item_location)
if delete_children:
_xmodule_recurse(item, lambda i: store.delete_item(i.location, delete_all_versions))
else:
store.delete_item(item.location, delete_all_versions)
# cdodge: we need to remove our parent's pointer to us so that it is no longer dangling
if delete_all_versions:
parent_locs = modulestore('direct').get_parent_locations(item_location, None)
for parent_loc in parent_locs:
parent = modulestore('direct').get_item(parent_loc)
item_url = item_location.url()
if item_url in parent.children:
children = parent.children
children.remove(item_url)
parent.children = children
modulestore('direct').update_children(parent.location, parent.children)
return JsonResponse()
示例6: _clone_modules
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [as 别名]
def _clone_modules(modulestore, modules, dest_location):
for module in modules:
original_loc = Location(module.location)
if original_loc.category != 'course':
module.location = module.location._replace(
tag=dest_location.tag, org=dest_location.org, course=dest_location.course)
else:
# on the course module we also have to update the module name
module.location = module.location._replace(
tag=dest_location.tag, org=dest_location.org, course=dest_location.course, name=dest_location.name)
print "Cloning module {0} to {1}....".format(original_loc, module.location)
# NOTE: usage of the the internal module.xblock_kvs._data does not include any 'default' values for the fields
modulestore.update_item(module.location, module.xblock_kvs._data)
# repoint children
if module.has_children:
new_children = []
for child_loc_url in module.children:
child_loc = Location(child_loc_url)
child_loc = child_loc._replace(
tag=dest_location.tag,
org=dest_location.org,
course=dest_location.course
)
new_children.append(child_loc.url())
modulestore.update_children(module.location, new_children)
# save metadata
modulestore.update_metadata(module.location, own_metadata(module))
示例7: _construct
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [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,
)
示例8: create_item
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [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: _clone_modules
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [as 别名]
def _clone_modules(modulestore, modules, source_location, dest_location):
for module in modules:
original_loc = Location(module.location)
if original_loc.category != 'course':
new_location = module.location._replace(
tag=dest_location.tag,
org=dest_location.org,
course=dest_location.course
)
module.scope_ids = module.scope_ids._replace(
def_id=new_location,
usage_id=new_location
)
else:
# on the course module we also have to update the module name
new_location = module.location._replace(
tag=dest_location.tag,
org=dest_location.org,
course=dest_location.course,
name=dest_location.name
)
module.scope_ids = module.scope_ids._replace(
def_id=new_location,
usage_id=new_location
)
print "Cloning module {0} to {1}....".format(original_loc, module.location)
# NOTE: usage of the the internal module.xblock_kvs._data does not include any 'default' values for the fields
data = module.xblock_kvs._data
if isinstance(data, basestring):
data = rewrite_nonportable_content_links(
source_location.course_id, dest_location.course_id, data)
modulestore.update_item(module.location, data)
# repoint children
if module.has_children:
new_children = []
for child_loc_url in module.children:
child_loc = Location(child_loc_url)
child_loc = child_loc._replace(
tag=dest_location.tag,
org=dest_location.org,
course=dest_location.course
)
new_children.append(child_loc.url())
modulestore.update_children(module.location, new_children)
# save metadata
modulestore.update_metadata(module.location, own_metadata(module))
示例10: test_metadata_inheritance
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [as 别名]
def test_metadata_inheritance(self):
module_store = modulestore('direct')
import_from_xml(module_store, 'common/test/data/', ['full'])
course = module_store.get_item(Location(
['i4x', 'edX', 'full', 'course', '6.002_Spring_2012', None]))
verticals = module_store.get_items(
['i4x', 'edX', 'full', 'vertical', None, None])
# let's assert on the metadata_inheritance on an existing vertical
for vertical in verticals:
self.assertEqual(course.lms.xqa_key, vertical.lms.xqa_key)
self.assertGreater(len(verticals), 0)
new_component_location = Location(
'i4x', 'edX', 'full', 'html', 'new_component')
source_template_location = Location(
'i4x', 'edx', 'templates', 'html', 'Blank_HTML_Page')
# crate a new module and add it as a child to a vertical
module_store.clone_item(
source_template_location, new_component_location)
parent = verticals[0]
module_store.update_children(parent.location, parent.children + [
new_component_location.url()])
# flush the cache
module_store.refresh_cached_metadata_inheritance_tree(
new_component_location)
new_module = module_store.get_item(new_component_location)
# check for grace period definition which should be defined at the
# course level
self.assertEqual(parent.lms.graceperiod, new_module.lms.graceperiod)
self.assertEqual(course.lms.xqa_key, new_module.lms.xqa_key)
#
# now let's define an override at the leaf node level
#
new_module.lms.graceperiod = timedelta(1)
module_store.update_metadata(
new_module.location, own_metadata(new_module))
# flush the cache and refetch
module_store.refresh_cached_metadata_inheritance_tree(
new_component_location)
new_module = module_store.get_item(new_component_location)
self.assertEqual(timedelta(1), new_module.lms.graceperiod)
示例11: export_all_for_course
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [as 别名]
def export_all_for_course(self, course_location, output_directory, assets_policy_file):
"""
Export all of this course's assets to the output_directory. Export all of the assets'
attributes to the policy file.
:param course_location: the Location of type 'course'
:param output_directory: the directory under which to put all the asset files
:param assets_policy_file: the filename for the policy file which should be in the same
directory as the other policy files.
"""
policy = {}
assets = self.get_all_content_for_course(course_location)
for asset in assets:
asset_location = Location(asset['_id'])
self.export(asset_location, output_directory)
for attr, value in asset.iteritems():
if attr not in ['_id', 'md5', 'uploadDate', 'length', 'chunkSize']:
policy.setdefault(asset_location.url(), {})[attr] = value
with open(assets_policy_file, 'w') as f:
json.dump(policy, f)
示例12: _construct
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [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)
示例13: test_encode_location
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [as 别名]
def test_encode_location(self):
loc = Location('i4x', 'org', 'course', 'category', 'name')
self.assertEqual(loc.url(), self.encoder.default(loc))
loc = Location('i4x', 'org', 'course', 'category', 'name', 'version')
self.assertEqual(loc.url(), self.encoder.default(loc))
示例14: compute_metadata_inheritance_tree
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [as 别名]
def compute_metadata_inheritance_tree(self, location):
'''
TODO (cdodge) This method can be deleted when the 'split module store' work has been completed
'''
# get all collections in the course, this query should not return any leaf nodes
# note this is a bit ugly as when we add new categories of containers, we have to add it here
query = {'_id.org': location.org,
'_id.course': location.course,
'_id.category': {'$in': ['course', 'chapter', 'sequential', 'vertical', 'videosequence',
'wrapper', 'problemset', 'conditional', 'randomize']}
}
# we just want the Location, children, and inheritable metadata
record_filter = {'_id': 1, 'definition.children': 1}
# just get the inheritable metadata since that is all we need for the computation
# this minimizes both data pushed over the wire
for field_name in InheritanceMixin.fields:
record_filter['metadata.{0}'.format(field_name)] = 1
# call out to the DB
resultset = self.collection.find(query, record_filter)
results_by_url = {}
root = None
# now go through the results and order them by the location url
for result in resultset:
location = Location(result['_id'])
# We need to collate between draft and non-draft
# i.e. draft verticals will have draft children but will have non-draft parents currently
location = location.replace(revision=None)
location_url = location.url()
if location_url in results_by_url:
existing_children = results_by_url[location_url].get('definition', {}).get('children', [])
additional_children = result.get('definition', {}).get('children', [])
total_children = existing_children + additional_children
results_by_url[location_url].setdefault('definition', {})['children'] = total_children
results_by_url[location.url()] = result
if location.category == 'course':
root = location.url()
# now traverse the tree and compute down the inherited metadata
metadata_to_inherit = {}
def _compute_inherited_metadata(url):
"""
Helper method for computing inherited metadata for a specific location url
"""
# check for presence of metadata key. Note that a given module may not yet be fully formed.
# example: update_item -> update_children -> update_metadata sequence on new item create
# if we get called here without update_metadata called first then 'metadata' hasn't been set
# as we're not fully transactional at the DB layer. Same comment applies to below key name
# check
my_metadata = results_by_url[url].get('metadata', {})
# go through all the children and recurse, but only if we have
# in the result set. Remember results will not contain leaf nodes
for child in results_by_url[url].get('definition', {}).get('children', []):
if child in results_by_url:
new_child_metadata = copy.deepcopy(my_metadata)
new_child_metadata.update(results_by_url[child].get('metadata', {}))
results_by_url[child]['metadata'] = new_child_metadata
metadata_to_inherit[child] = new_child_metadata
_compute_inherited_metadata(child)
else:
# this is likely a leaf node, so let's record what metadata we need to inherit
metadata_to_inherit[child] = my_metadata
if root is not None:
_compute_inherited_metadata(root)
return metadata_to_inherit
示例15: clone_course
# 需要导入模块: from xmodule.modulestore import Location [as 别名]
# 或者: from xmodule.modulestore.Location import url [as 别名]
def clone_course(modulestore, contentstore, source_location, dest_location, delete_original=False):
# first check to see if the modulestore is Mongo backed
if not isinstance(modulestore, MongoModuleStore):
raise Exception("Expected a MongoModuleStore in the runtime. Aborting....")
# check to see if the dest_location exists as an empty course
# we need an empty course because the app layers manage the permissions and users
if not modulestore.has_item(dest_location):
raise Exception("An empty course at {0} must have already been created. Aborting...".format(dest_location))
# verify that the dest_location really is an empty course, which means only one with an optional 'overview'
dest_modules = modulestore.get_items([dest_location.tag, dest_location.org, dest_location.course, None, None, None])
basically_empty = True
for module in dest_modules:
if module.location.category == 'course' or (module.location.category == 'about'
and module.location.name == 'overview'):
continue
basically_empty = False
break
if not basically_empty:
raise Exception("Course at destination {0} is not an empty course. You can only clone into an empty course. Aborting...".format(dest_location))
# check to see if the source course is actually there
if not modulestore.has_item(source_location):
raise Exception("Cannot find a course at {0}. Aborting".format(source_location))
# Get all modules under this namespace which is (tag, org, course) tuple
modules = modulestore.get_items([source_location.tag, source_location.org, source_location.course, None, None, None])
for module in modules:
original_loc = Location(module.location)
if original_loc.category != 'course':
module.location = module.location._replace(tag=dest_location.tag, org=dest_location.org,
course=dest_location.course)
else:
# on the course module we also have to update the module name
module.location = module.location._replace(tag=dest_location.tag, org=dest_location.org,
course=dest_location.course, name=dest_location.name)
print "Cloning module {0} to {1}....".format(original_loc, module.location)
modulestore.update_item(module.location, module._model_data._kvs._data)
# repoint children
if module.has_children:
new_children = []
for child_loc_url in module.children:
child_loc = Location(child_loc_url)
child_loc = child_loc._replace(
tag=dest_location.tag,
org=dest_location.org,
course=dest_location.course
)
new_children.append(child_loc.url())
modulestore.update_children(module.location, new_children)
# save metadata
modulestore.update_metadata(module.location, module._model_data._kvs._metadata)
# now iterate through all of the assets and clone them
# first the thumbnails
thumbs = contentstore.get_all_content_thumbnails_for_course(source_location)
for thumb in thumbs:
thumb_loc = Location(thumb["_id"])
content = contentstore.find(thumb_loc)
content.location = content.location._replace(org=dest_location.org,
course=dest_location.course)
print "Cloning thumbnail {0} to {1}".format(thumb_loc, content.location)
contentstore.save(content)
# now iterate through all of the assets, also updating the thumbnail pointer
assets = contentstore.get_all_content_for_course(source_location)
for asset in assets:
asset_loc = Location(asset["_id"])
content = contentstore.find(asset_loc)
content.location = content.location._replace(org=dest_location.org,
course=dest_location.course)
# be sure to update the pointer to the thumbnail
if content.thumbnail_location is not None:
content.thumbnail_location = content.thumbnail_location._replace(org=dest_location.org,
course=dest_location.course)
print "Cloning asset {0} to {1}".format(asset_loc, content.location)
contentstore.save(content)
return True