本文整理汇总了Python中opaque_keys.InvalidKeyError方法的典型用法代码示例。如果您正苦于以下问题:Python opaque_keys.InvalidKeyError方法的具体用法?Python opaque_keys.InvalidKeyError怎么用?Python opaque_keys.InvalidKeyError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类opaque_keys
的用法示例。
在下文中一共展示了opaque_keys.InvalidKeyError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: site_course_helper
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [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
示例2: validate_user
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [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)
示例3: handle
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [as 别名]
def handle(self, *args, **options):
if len(args) != 1 and len(args) != 2:
raise CommandError("delete_course requires one or more arguments: <course_id> |commit|")
try:
course_key = CourseKey.from_string(args[0])
except InvalidKeyError:
course_key = SlashSeparatedCourseKey.from_deprecated_string(args[0])
commit = False
if len(args) == 2:
commit = args[1] == 'commit'
if commit:
print('Actually going to delete the course from DB....')
if query_yes_no("Deleting course {0}. Confirm?".format(course_key), default="no"):
if query_yes_no("Are you sure. This action cannot be undone!", default="no"):
delete_course_and_groups(course_key, ModuleStoreEnum.UserID.mgmt_command)
示例4: handle
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [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)
示例5: assert_course_creation_failed
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [as 别名]
def assert_course_creation_failed(self, error_message):
"""
Checks that the course did not get created
"""
test_enrollment = False
try:
course_id = _get_course_id(self.course_data)
initially_enrolled = CourseEnrollment.is_enrolled(self.user, course_id)
test_enrollment = True
except InvalidKeyError:
# b/c the intent of the test with bad chars isn't to test auth but to test the handler, ignore
pass
resp = self.client.ajax_post('/course/', self.course_data)
self.assertEqual(resp.status_code, 200)
data = parse_json(resp)
self.assertRegexpMatches(data['ErrMsg'], error_message)
if test_enrollment:
# One test case involves trying to create the same course twice. Hence for that course,
# the user will be enrolled. In the other cases, initially_enrolled will be False.
self.assertEqual(initially_enrolled, CourseEnrollment.is_enrolled(self.user, course_id))
示例6: get_filename_safe_course_id
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [as 别名]
def get_filename_safe_course_id(course_id, replacement_char='_'):
"""
Create a representation of a course_id that can be used safely in a filepath.
"""
try:
course_key = CourseKey.from_string(course_id)
# Ignore the namespace of the course_id altogether, for backwards compatibility.
filename = course_key._to_string() # pylint: disable=protected-access
except InvalidKeyError:
# If the course_id doesn't parse, we will still return a value here.
filename = course_id
# The safest characters are A-Z, a-z, 0-9, <underscore>, <period> and <hyphen>.
# We represent the first four with \w.
# TODO: Once we support courses with unicode characters, we will need to revisit this.
return re.sub(r'[^\w\.\-]', unicode(replacement_char), filename)
示例7: get_course_key_from_url
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [as 别名]
def get_course_key_from_url(url):
"""
Extracts the course from the given `url`, if possible.
"""
url = url or ''
match = COURSE_REGEX.match(url)
course_key = None
if match:
course_id_string = match.group('course_id')
try:
course_key = CourseKey.from_string(course_id_string)
except InvalidKeyError:
pass
return course_key
示例8: _get_courses
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [as 别名]
def _get_courses(self):
course_keys = []
course_ids = self.request.GET.getlist('course_id')
for course_id in course_ids:
try:
course_run_key = CourseKey.from_string(course_id)
except InvalidKeyError:
# An `InvalidKeyError` is thrown because this course key not a course run key
# We will get the title from the discovery.
try:
course = get_course_detail(self.request.site, course_id)
course_keys.append(course.get('title'))
except (ReqConnectionError, SlumberHttpBaseException, Timeout) as exc:
logger.exception(
'[Account activation failure] User tried to excess the course from discovery and failed.'
'User: %s, course: %s, Message: %s',
self.request.user.id,
course_id,
exc
)
raise Http404
else:
course_run = get_object_or_404(Course, id=course_run_key)
course_keys.append(course_run.name)
return course_keys
示例9: is_course_run_id
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [as 别名]
def is_course_run_id(self, course_id):
"""
Returns True if the course_id is in the correct format of a course_run_id, false otherwise.
Arguments:
course_id (str): The course_key or course run id
Returns:
(Boolean): True or False
"""
try:
# Check if we have a course ID or a course run ID
CourseKey.from_string(course_id)
except InvalidKeyError:
# The ID we have is for a course instead of a course run
return False
# If here, the course_id is a course_run_id
return True
示例10: parse_edx_key
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [as 别名]
def parse_edx_key(edx_course_key):
"""
Attempts to parse a CourseRun's edx_course_key as an edX opaque key and return the portion
of the key that indicates the course's semester/year
Args:
edx_course_key (str): An edX course key (CourseRun.edx_course_key)
Returns:
str: The 'run' portion of a parsed CourseKey (opaque_keys.edx.keys.CourseKey#run),
eg: '1T2016'. Return None if the parse fails.
"""
try:
course_key = CourseKey.from_string(edx_course_key)
except InvalidKeyError:
return None
return course_key.run if course_key else None
示例11: test_from_invalid_string
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [as 别名]
def test_from_invalid_string(self):
with pytest.raises(InvalidKeyError):
as_course_key('some invalid string')
示例12: download_transcripts
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [as 别名]
def download_transcripts(request):
"""
Passes to user requested transcripts file.
Raises Http404 if unsuccessful.
"""
locator = request.GET.get('locator')
if not locator:
log.debug('GET data without "locator" property.')
raise Http404
try:
item = _get_item(request, request.GET)
except (InvalidKeyError, ItemNotFoundError):
log.debug("Can't find item by locator.")
raise Http404
subs_id = request.GET.get('subs_id')
if not subs_id:
log.debug('GET data without "subs_id" property.')
raise Http404
if item.category != 'video':
log.debug('transcripts are supported only for video" modules.')
raise Http404
filename = 'subs_{0}.srt.sjson'.format(subs_id)
content_location = StaticContent.compute_location(item.location.course_key, filename)
try:
sjson_transcripts = contentstore().find(content_location)
log.debug("Downloading subs for %s id", subs_id)
str_subs = generate_srt_from_sjson(json.loads(sjson_transcripts.data), speed=1.0)
if not str_subs:
log.debug('generate_srt_from_sjson produces no subtitles')
raise Http404
response = HttpResponse(str_subs, content_type='application/x-subrip')
response['Content-Disposition'] = 'attachment; filename="{0}.srt"'.format(subs_id)
return response
except NotFoundError:
log.debug("Can't find content in storage for %s subs", subs_id)
raise Http404
示例13: _validate_transcripts_data
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [as 别名]
def _validate_transcripts_data(request):
"""
Validates, that request contains all proper data for transcripts processing.
Returns tuple of 3 elements::
data: dict, loaded json from request,
videos: parsed `data` to useful format,
item: video item from storage
Raises `TranscriptsRequestValidationException` if validation is unsuccessful
or `PermissionDenied` if user has no access.
"""
data = json.loads(request.GET.get('data', '{}'))
if not data:
raise TranscriptsRequestValidationException(_('Incoming video data is empty.'))
try:
item = _get_item(request, data)
except (InvalidKeyError, ItemNotFoundError):
raise TranscriptsRequestValidationException(_("Can't find item by locator."))
if item.category != 'video':
raise TranscriptsRequestValidationException(_('Transcripts are supported only for "video" modules.'))
# parse data form request.GET.['data']['video'] to useful format
videos = {'youtube': '', 'html5': {}}
for video_data in data.get('videos'):
if video_data['type'] == 'youtube':
videos['youtube'] = video_data['video']
else: # do not add same html5 videos
if videos['html5'].get('video') != video_data['video']:
videos['html5'][video_data['video']] = video_data['mode']
return data, videos, item
示例14: save_transcripts
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [as 别名]
def save_transcripts(request):
"""
Saves video module with updated values of fields.
Returns: status `Success` or status `Error` and HTTP 400.
"""
response = {'status': 'Error'}
data = json.loads(request.GET.get('data', '{}'))
if not data:
return error_response(response, 'Incoming video data is empty.')
try:
item = _get_item(request, data)
except (InvalidKeyError, ItemNotFoundError):
return error_response(response, "Can't find item by locator.")
metadata = data.get('metadata')
if metadata is not None:
new_sub = metadata.get('sub')
for metadata_key, value in metadata.items():
setattr(item, metadata_key, value)
item.save_with_metadata(request.user) # item becomes updated with new values
if new_sub:
manage_video_subtitles_save(item, request.user)
else:
# If `new_sub` is empty, it means that user explicitly does not want to use
# transcripts for current video ids and we remove all transcripts from storage.
current_subs = data.get('current_subs')
if current_subs is not None:
for sub in current_subs:
remove_subs_from_store(sub, item)
response['status'] = 'Success'
return JsonResponse(response)
示例15: course_key_from_arg
# 需要导入模块: import opaque_keys [as 别名]
# 或者: from opaque_keys import InvalidKeyError [as 别名]
def course_key_from_arg(self, arg):
"""
Convert the command line arg into a course key
"""
try:
return CourseKey.from_string(arg)
except InvalidKeyError:
return SlashSeparatedCourseKey.from_deprecated_string(arg)