本文整理汇总了Python中xmodule.modulestore.django.loc_mapper函数的典型用法代码示例。如果您正苦于以下问题:Python loc_mapper函数的具体用法?Python loc_mapper怎么用?Python loc_mapper使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了loc_mapper函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_all_course_role_groupnames
def get_all_course_role_groupnames(location, role, use_filter=True):
'''
Get all of the possible groupnames for this role location pair. If use_filter==True,
only return the ones defined in the groups collection.
'''
location = Locator.to_locator_or_location(location)
groupnames = []
if isinstance(location, Location):
try:
groupnames.append('{0}_{1}'.format(role, location.course_id))
except InvalidLocationError: # will occur on old locations where location is not of category course
pass
try:
locator = loc_mapper().translate_location(location.course_id, location, False, False)
groupnames.append('{0}_{1}'.format(role, locator.package_id))
except (InvalidLocationError, ItemNotFoundError):
pass
# least preferred role_course format for legacy reasons
groupnames.append('{0}_{1}'.format(role, location.course))
elif isinstance(location, CourseLocator):
groupnames.append('{0}_{1}'.format(role, location.package_id))
old_location = loc_mapper().translate_locator_to_location(location, get_course=True)
if old_location:
# the slashified version of the course_id (myu/mycourse/myrun)
groupnames.append('{0}_{1}'.format(role, old_location.course_id))
# add the least desirable but sometimes occurring format.
groupnames.append('{0}_{1}'.format(role, old_location.course))
# filter to the ones which exist
default = groupnames[0]
if use_filter:
groupnames = [group.name for group in Group.objects.filter(name__in=groupnames)]
return groupnames, default
示例2: delete_course_and_groups
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)
示例3: course_info_handler
def course_info_handler(request, tag=None, course_id=None, branch=None, version_guid=None, block=None):
"""
GET
html: return html for editing the course info handouts and updates.
"""
course_location = BlockUsageLocator(course_id=course_id, branch=branch, version_guid=version_guid, usage_id=block)
course_old_location = loc_mapper().translate_locator_to_location(course_location)
if 'text/html' in request.META.get('HTTP_ACCEPT', 'text/html'):
if not has_access(request.user, course_location):
raise PermissionDenied()
course_module = modulestore().get_item(course_old_location)
handouts_old_location = course_old_location.replace(category='course_info', name='handouts')
handouts_locator = loc_mapper().translate_location(
course_old_location.course_id, handouts_old_location, False, True
)
update_location = course_old_location.replace(category='course_info', name='updates')
update_locator = loc_mapper().translate_location(
course_old_location.course_id, update_location, False, True
)
return render_to_response(
'course_info.html',
{
'context_course': course_module,
'updates_url': update_locator.url_reverse('course_info_update/'),
'handouts_locator': handouts_locator,
'base_asset_url': StaticContent.get_base_url_path_for_course_assets(course_old_location) + '/'
}
)
else:
return HttpResponseBadRequest("Only supports html requests")
示例4: check_equality
def check_equality(source_locator, duplicate_locator):
original_item = self.get_item_from_modulestore(source_locator, draft=True)
duplicated_item = self.get_item_from_modulestore(duplicate_locator, draft=True)
self.assertNotEqual(
original_item.location,
duplicated_item.location,
"Location of duplicate should be different from original"
)
# Set the location and display name to be the same so we can make sure the rest of the duplicate is equal.
duplicated_item.location = original_item.location
duplicated_item.display_name = original_item.display_name
# Children will also be duplicated, so for the purposes of testing equality, we will set
# the children to the original after recursively checking the children.
if original_item.has_children:
self.assertEqual(
len(original_item.children),
len(duplicated_item.children),
"Duplicated item differs in number of children"
)
for i in xrange(len(original_item.children)):
source_locator = loc_mapper().translate_location(
self.course.location.course_id, Location(original_item.children[i]), False, True
)
duplicate_locator = loc_mapper().translate_location(
self.course.location.course_id, Location(duplicated_item.children[i]), False, True
)
if not check_equality(source_locator, duplicate_locator):
return False
duplicated_item.children = original_item.children
return original_item == duplicated_item
示例5: course_info_handler
def course_info_handler(request, tag=None, package_id=None, branch=None, version_guid=None, block=None):
"""
GET
html: return html for editing the course info handouts and updates.
"""
__, course_module = _get_locator_and_course(package_id, branch, version_guid, block, request.user)
if "text/html" in request.META.get("HTTP_ACCEPT", "text/html"):
handouts_old_location = course_module.location.replace(category="course_info", name="handouts")
handouts_locator = loc_mapper().translate_location(
course_module.location.course_id, handouts_old_location, False, True
)
update_location = course_module.location.replace(category="course_info", name="updates")
update_locator = loc_mapper().translate_location(course_module.location.course_id, update_location, False, True)
return render_to_response(
"course_info.html",
{
"context_course": course_module,
"updates_url": update_locator.url_reverse("course_info_update/"),
"handouts_locator": handouts_locator,
"base_asset_url": StaticContent.get_base_url_path_for_course_assets(course_module.location) + "/",
},
)
else:
return HttpResponseBadRequest("Only supports html requests")
示例6: get_all_course_role_groupnames
def get_all_course_role_groupnames(location, role, use_filter=True):
'''
Get all of the possible groupnames for this role location pair. If use_filter==True,
only return the ones defined in the groups collection.
'''
location = Locator.to_locator_or_location(location)
# hack: check for existence of a group name in the legacy LMS format <role>_<course>
# if it exists, then use that one, otherwise use a <role>_<course_id> which contains
# more information
groupnames = []
try:
groupnames.append('{0}_{1}'.format(role, location.course_id))
except InvalidLocationError: # will occur on old locations where location is not of category course
pass
if isinstance(location, Location):
# least preferred role_course format
groupnames.append('{0}_{1}'.format(role, location.course))
try:
locator = loc_mapper().translate_location(location.course_id, location, False, False)
groupnames.append('{0}_{1}'.format(role, locator.course_id))
except (InvalidLocationError, ItemNotFoundError):
pass
elif isinstance(location, CourseLocator):
old_location = loc_mapper().translate_locator_to_location(location, get_course=True)
if old_location:
# the slashified version of the course_id (myu/mycourse/myrun)
groupnames.append('{0}_{1}'.format(role, old_location.course_id))
# add the least desirable but sometimes occurring format.
groupnames.append('{0}_{1}'.format(role, old_location.course))
# filter to the ones which exist
default = groupnames[0]
if use_filter:
groupnames = [group for group in groupnames if Group.objects.filter(name=group).exists()]
return groupnames, default
示例7: course_info_handler
def course_info_handler(request, tag=None, package_id=None, branch=None, version_guid=None, block=None):
"""
GET
html: return html for editing the course info handouts and updates.
"""
__, course_module = _get_locator_and_course(
package_id, branch, version_guid, block, request.user
)
if 'text/html' in request.META.get('HTTP_ACCEPT', 'text/html'):
handouts_old_location = course_module.location.replace(category='course_info', name='handouts')
handouts_locator = loc_mapper().translate_location(
course_module.location.course_id, handouts_old_location, False, True
)
update_location = course_module.location.replace(category='course_info', name='updates')
update_locator = loc_mapper().translate_location(
course_module.location.course_id, update_location, False, True
)
return render_to_response(
'course_info.html',
{
'context_course': course_module,
'updates_url': update_locator.url_reverse('course_info_update/'),
'handouts_locator': handouts_locator,
'base_asset_url': StaticContent.get_base_url_path_for_course_assets(course_module.location) + '/'
}
)
else:
return HttpResponseBadRequest("Only supports html requests")
示例8: test_post_course_update
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)
示例9: test_get_course_list_with_same_course_id
def test_get_course_list_with_same_course_id(self):
"""
Test getting courses with same id but with different name case. Then try to delete one of them and
check that it is properly deleted and other one is accessible
"""
request = self.factory.get('/course')
request.user = self.user
course_location_caps = Location(['i4x', 'Org', 'COURSE', 'course', 'Run'])
self._create_course_with_access_groups(course_location_caps, 'group_name_with_dots', self.user)
# get courses through iterating all courses
courses_list = _accessible_courses_list(request)
self.assertEqual(len(courses_list), 1)
# get courses by reversing group name formats
courses_list_by_groups = _accessible_courses_list_from_groups(request)
self.assertEqual(len(courses_list_by_groups), 1)
# check both course lists have same courses
self.assertEqual(courses_list, courses_list_by_groups)
# now create another course with same course_id but different name case
course_location_camel = Location(['i4x', 'Org', 'Course', 'course', 'Run'])
self._create_course_with_access_groups(course_location_camel, 'group_name_with_dots', self.user)
# test that get courses through iterating all courses returns both courses
courses_list = _accessible_courses_list(request)
self.assertEqual(len(courses_list), 2)
# test that get courses by reversing group name formats returns only one course
courses_list_by_groups = _accessible_courses_list_from_groups(request)
self.assertEqual(len(courses_list_by_groups), 1)
course_locator = loc_mapper().translate_location(course_location_caps.course_id, course_location_caps)
outline_url = course_locator.url_reverse('course/')
# now delete first course (course_location_caps) and check that it is no longer accessible
delete_course_and_groups(course_location_caps.course_id, commit=True)
# add user to this course instructor group since he was removed from that group on course delete
instructor_group_name = CourseInstructorRole(course_locator)._group_names[0] # pylint: disable=protected-access
group, __ = Group.objects.get_or_create(name=instructor_group_name)
self.user.groups.add(group)
# test that get courses through iterating all courses now returns one course
courses_list = _accessible_courses_list(request)
self.assertEqual(len(courses_list), 1)
# test that get courses by reversing group name formats also returns one course
courses_list_by_groups = _accessible_courses_list_from_groups(request)
self.assertEqual(len(courses_list_by_groups), 1)
# now check that deleted course in not accessible
response = self.client.get(outline_url, HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 403)
# now check that other course in accessible
course_locator = loc_mapper().translate_location(course_location_camel.course_id, course_location_camel)
outline_url = course_locator.url_reverse('course/')
response = self.client.get(outline_url, HTTP_ACCEPT='application/json')
self.assertEqual(response.status_code, 200)
示例10: tabs_handler
def tabs_handler(request, tag=None, package_id=None, branch=None, version_guid=None, block=None):
"""
The restful handler for static tabs.
GET
html: return page for editing static tabs
json: not supported
PUT or POST
json: update the tab order. It is expected that the request body contains a JSON-encoded dict with entry "tabs".
The value for "tabs" is an array of tab locators, indicating the desired order of the tabs.
Creating a tab, deleting a tab, or changing its contents is not supported through this method.
Instead use the general xblock URL (see item.xblock_handler).
"""
locator = BlockUsageLocator(package_id=package_id, branch=branch, version_guid=version_guid, block_id=block)
if not has_course_access(request.user, locator):
raise PermissionDenied()
old_location = loc_mapper().translate_locator_to_location(locator)
store = get_modulestore(old_location)
course_item = store.get_item(old_location)
if 'application/json' in request.META.get('HTTP_ACCEPT', 'application/json'):
if request.method == 'GET':
raise NotImplementedError('coming soon')
else:
if 'tabs' in request.json:
return reorder_tabs_handler(course_item, request)
elif 'tab_id_locator' in request.json:
return edit_tab_handler(course_item, request)
else:
raise NotImplementedError('Creating or changing tab content is not supported.')
elif request.method == 'GET': # assume html
# get all tabs from the tabs list: static tabs (a.k.a. user-created tabs) and built-in tabs
# present in the same order they are displayed in LMS
tabs_to_render = []
for tab in CourseTabList.iterate_displayable_cms(
course_item,
settings,
):
if isinstance(tab, StaticTab):
# static tab needs its locator information to render itself as an xmodule
static_tab_loc = old_location.replace(category='static_tab', name=tab.url_slug)
tab.locator = loc_mapper().translate_location(
course_item.location.course_id, static_tab_loc, False, True
)
tabs_to_render.append(tab)
return render_to_response('edit-tabs.html', {
'context_course': course_item,
'tabs_to_render': tabs_to_render,
'course_locator': locator,
'lms_link': get_lms_link_for_item(course_item.location),
})
else:
return HttpResponseNotFound()
示例11: _infer_course_id_try
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
示例12: get_items
def get_items(self, location, course_id=None, depth=0, qualifiers=None):
"""
Returns a list of XModuleDescriptor instances for the items
that match location. Any element of location that is None is treated
as a wildcard that matches any value. NOTE: don't use this to look for courses
as the course_id is required. Use get_courses.
location: either a Location possibly w/ None as wildcards for category or name or
a Locator with at least a package_id and branch but possibly no block_id.
depth: An argument that some module stores may use to prefetch
descendents of the queried modules for more efficient results later
in the request. The depth is counted in the number of calls to
get_children() to cache. None indicates to cache all descendents
"""
if not (course_id or hasattr(location, 'package_id')):
raise Exception("Must pass in a course_id when calling get_items()")
store = self._get_modulestore_for_courseid(course_id or getattr(location, 'package_id'))
# translate won't work w/ missing fields so work around it
if store.reference_type == Location:
if not self.use_locations:
if getattr(location, 'block_id', False):
location = self._incoming_reference_adaptor(store, course_id, location)
else:
# get the course's location
location = loc_mapper().translate_locator_to_location(location, get_course=True)
# now remove the unknowns
location = location.replace(
category=qualifiers.get('category', None),
name=None
)
else:
if self.use_locations:
if not isinstance(location, Location):
location = Location(location)
try:
location.ensure_fully_specified()
location = loc_mapper().translate_location(
course_id, location, location.revision == 'published', True
)
except InsufficientSpecificationError:
# construct the Locator by hand
if location.category is not None and qualifiers.get('category', False):
qualifiers['category'] = location.category
location = loc_mapper().translate_location_to_course_locator(
course_id, location, location.revision == 'published'
)
xblocks = store.get_items(location, course_id, depth, qualifiers)
xblocks = [self._outgoing_xblock_adaptor(store, course_id, xblock) for xblock in xblocks]
return xblocks
示例13: ensure_loc_maps_exist
def ensure_loc_maps_exist(self, store_name):
"""
Ensure location maps exist for every course in the modulestore whose
name is the given name (mostly used for 'xml'). It creates maps for any
missing ones.
NOTE: will only work if the given store is Location based. If it's not,
it raises NotImplementedError
"""
store = self.modulestores[store_name]
if store.reference_type != Location:
raise ValueError(u"Cannot create maps from %s" % store.reference_type)
for course in store.get_courses():
loc_mapper().translate_location(course.location.course_id, course.location)
示例14: _get_module_info
def _get_module_info(usage_loc, rewrite_static_links=True):
"""
metadata, data, id representation of a leaf module fetcher.
:param usage_loc: A BlockUsageLocator
"""
old_location = loc_mapper().translate_locator_to_location(usage_loc)
store = get_modulestore(old_location)
try:
module = store.get_item(old_location)
except ItemNotFoundError:
if old_location.category in CREATE_IF_NOT_FOUND:
# Create a new one for certain categories only. Used for course info handouts.
store.create_and_save_xmodule(old_location)
module = store.get_item(old_location)
else:
raise
data = getattr(module, 'data', '')
if rewrite_static_links:
# we pass a partially bogus course_id as we don't have the RUN information passed yet
# through the CMS. Also the contentstore is also not RUN-aware at this point in time.
data = replace_static_urls(
data,
None,
course_id=module.location.org + '/' + module.location.course + '/BOGUS_RUN_REPLACE_WHEN_AVAILABLE'
)
# Note that children aren't being returned until we have a use case.
return {
'id': unicode(usage_loc),
'data': data,
'metadata': own_metadata(module)
}
示例15: mapper
def mapper(found_id):
"""
Convert the found id to BlockUsageLocator block_id
"""
location = from_base_addr.replace(category=None, name=found_id)
# NOTE without category, it cannot create a new mapping if there's not one already
return loc_mapper().translate_location(course_id, location).block_id