本文整理汇总了Python中models.transforms.json_to_dict函数的典型用法代码示例。如果您正苦于以下问题:Python json_to_dict函数的具体用法?Python json_to_dict怎么用?Python json_to_dict使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了json_to_dict函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_reject_bad_boolean
def test_reject_bad_boolean(self):
schema = wrap_properties({'field': {'type': 'boolean'}})
source = {'field': 'cat'}
try:
transforms.json_to_dict(source, schema)
self.fail('Expected ValueException')
except ValueError as e:
self.assertEqual(str(e), 'Bad boolean value for field: cat')
示例2: test_reject_bad_number
def test_reject_bad_number(self):
schema = wrap_properties({'field': {'type': 'number'}})
source = {'field': 'cat'}
try:
transforms.json_to_dict(source, schema)
self.fail('Expected ValueException')
except ValueError as e:
self.assertEqual(str(e), 'could not convert string to float: cat')
示例3: test_convert_date
def test_convert_date(self):
schema = wrap_properties({'field': {'type': 'date'}})
source = {'field': '2005/03/01'}
result = transforms.json_to_dict(source, schema)
self.assertEqual(len(result), 1)
self.assertEqual(result['field'], datetime.date(2005, 3, 1))
source = {'field': '2005-03-01'}
result = transforms.json_to_dict(source, schema)
self.assertEqual(result['field'], datetime.date(2005, 3, 1))
示例4: put
def put(self):
"""Store a question group in the datastore in response to a PUT."""
request = transforms.loads(self.request.get('request'))
key = request.get('key')
if not self.assert_xsrf_token_or_fail(
request, self.XSRF_TOKEN, {'key': key}):
return
if not CourseOutlineRights.can_edit(self):
transforms.send_json_response(
self, 401, 'Access denied.', {'key': key})
return
payload = request.get('payload')
question_group_dict = transforms.json_to_dict(
transforms.loads(payload),
self.get_schema().get_json_schema_dict())
validation_errors = self.validate(question_group_dict, key)
if validation_errors:
self.validation_error('\n'.join(validation_errors), key=key)
return
assert self.SCHEMA_VERSION == question_group_dict.get('version')
if key:
question_group = QuestionGroupDTO(key, question_group_dict)
else:
question_group = QuestionGroupDTO(None, question_group_dict)
key_after_save = QuestionGroupDAO.save(question_group)
transforms.send_json_response(
self, 200, 'Saved.', payload_dict={'key': key_after_save})
示例5: put
def put(self):
"""A PUT REST method shared by all unit types."""
request = transforms.loads(self.request.get('request'))
key = request.get('key')
if not self.assert_xsrf_token_or_fail(
request, 'put-unit', {'key': key}):
return
if not CourseOutlineRights.can_edit(self):
transforms.send_json_response(
self, 401, 'Access denied.', {'key': key})
return
unit = courses.Course(self).find_unit_by_id(key)
if not unit:
transforms.send_json_response(
self, 404, 'Object not found.', {'key': key})
return
payload = request.get('payload')
updated_unit_dict = transforms.json_to_dict(
transforms.loads(payload), self.SCHEMA_DICT)
errors = []
self.apply_updates(unit, updated_unit_dict, errors)
if not errors:
course = courses.Course(self)
assert course.update_unit(unit)
course.save()
common_utils.run_hooks(self.POST_SAVE_HOOKS, unit)
transforms.send_json_response(self, 200, 'Saved.')
else:
transforms.send_json_response(self, 412, '\n'.join(errors))
示例6: put
def put(self):
"""A PUT REST method shared by all unit types."""
request = transforms.loads(self.request.get('request'))
key = request.get('key')
if not self.assert_xsrf_token_or_fail(
request, 'put-unit', {'key': key}):
return
if not CourseOutlineRights.can_edit(self):
transforms.send_json_response(
self, 401, 'Access denied.', {'key': key})
return
unit = courses.Course(self).find_unit_by_id(key)
if not unit:
transforms.send_json_response(
self, 404, 'Object not found.', {'key': key})
return
payload = request.get('payload')
errors = []
try:
updated_unit_dict = transforms.json_to_dict(
transforms.loads(payload), self.SCHEMA_DICT)
self.apply_updates(unit, updated_unit_dict, errors)
except (TypeError, ValueError), ex:
errors.append(str(ex))
示例7: put
def put(self):
"""Handles REST PUT verb with JSON payload."""
request = json.loads(self.request.get('request'))
key = request.get('key')
if not self.assert_xsrf_token_or_fail(
request, 'announcement-put', {'key': key}):
return
if not AnnouncementsRights.can_edit(self):
transforms.send_json_response(
self, 401, 'Access denied.', {'key': key})
return
entity = AnnouncementEntity.get(key)
if not entity:
transforms.send_json_response(
self, 404, 'Object not found.', {'key': key})
return
payload = request.get('payload')
transforms.dict_to_entity(entity, transforms.json_to_dict(
json.loads(payload), SCHEMA_DICT))
entity.put()
transforms.send_json_response(self, 200, 'Saved.')
示例8: test_missing_required_fields_are_rejected
def test_missing_required_fields_are_rejected(self):
schema = wrap_properties(
{'req_field': {'type': 'boolean', 'optional': 'false'}})
try:
transforms.json_to_dict({}, schema)
self.fail('Expected ValueError')
except ValueError as e:
self.assertEqual(str(e), 'Missing required attribute: req_field')
schema = wrap_properties(
{'req_field': {'type': 'boolean'}})
try:
transforms.json_to_dict({}, schema)
self.fail('Expected ValueError')
except ValueError as e:
self.assertEqual(str(e), 'Missing required attribute: req_field')
示例9: put
def put(self):
"""A PUT REST method shared by all unit types."""
request = transforms.loads(self.request.get("request"))
key = request.get("key")
if not self.assert_xsrf_token_or_fail(request, "put-unit", {"key": key}):
return
if not CourseOutlineRights.can_edit(self):
transforms.send_json_response(self, 401, "Access denied.", {"key": key})
return
unit = courses.Course(self).find_unit_by_id(key)
if not unit:
transforms.send_json_response(self, 404, "Object not found.", {"key": key})
return
payload = request.get("payload")
updated_unit_dict = transforms.json_to_dict(transforms.loads(payload), self.SCHEMA_DICT)
errors = []
self.apply_updates(unit, updated_unit_dict, errors)
if not errors:
course = courses.Course(self)
assert course.update_unit(unit)
course.save()
transforms.send_json_response(self, 200, "Saved.")
else:
transforms.send_json_response(self, 412, "\n".join(errors))
示例10: put
def put(self):
"""A PUT REST method shared by all unit types."""
request = transforms.loads(self.request.get("request"))
key = request.get("key")
if not self.assert_xsrf_token_or_fail(request, "put-unit", {"key": key}):
return
if not self.can_edit(self.app_context):
transforms.send_json_response(self, 401, "Access denied.", {"key": key})
return
unit = courses.Course(self).find_unit_by_id(key)
if not unit:
transforms.send_json_response(self, 404, "Object not found.", {"key": key})
return
payload = request.get("payload")
errors = []
course = courses.Course(self)
try:
schema = self.get_schema(course, key)
updated_unit_dict = transforms.json_to_dict(transforms.loads(payload), schema.get_json_schema_dict())
schema.redact_entity_to_schema(updated_unit_dict)
self.apply_updates(unit, updated_unit_dict, errors)
except (TypeError, ValueError), ex:
errors.append(str(ex))
示例11: _add_query_filters
def _add_query_filters(cls, source_context, schema, page_number, query):
for filter_spec in source_context.filters:
parts = cls.FILTER_RE.match(filter_spec)
if not parts:
raise ValueError(
'Filter specification "%s" ' % filter_spec +
'is not of the form: <name><op><value>')
name, op, value = parts.groups()
if op not in cls.SUPPORTED_OPERATIONS:
raise ValueError(
'Filter specification "%s" ' % filter_spec +
'uses an unsupported comparison operation "%s"' % op)
if name not in schema:
raise ValueError(
'Filter specification "%s" ' % filter_spec +
'calls for field "%s" ' % name +
'which is not in the schema for '
'type "%s"' % cls.get_entity_class().__name__)
if value == '':
converted_value = None
else:
converted_value = transforms.json_to_dict(
{name: value},
{'properties': {name: schema[name]}})[name]
query.filter('%s %s' % (name, op), converted_value)
示例12: put
def put(self):
"""Handles PUT REST verb to save lesson and associated activity."""
request = transforms.loads(self.request.get('request'))
key = request.get('key')
if not self.assert_xsrf_token_or_fail(
request, 'lesson-edit', {'key': key}):
return
if not roles.Roles.is_course_admin(self.app_context):
transforms.send_json_response(
self, 401, 'Access denied.', {'key': key})
return
course = courses.Course(self)
lesson = course.find_lesson_by_id(None, key)
if not lesson:
transforms.send_json_response(
self, 404, 'Object not found.', {'key': key})
return
payload = request.get('payload')
updates_dict = transforms.json_to_dict(
transforms.loads(payload),
self.get_schema(course, key).get_json_schema_dict())
lesson.title = updates_dict['title']
lesson.unit_id = updates_dict['unit_id']
lesson.scored = (updates_dict['scored'] == 'scored')
lesson.objectives = updates_dict['objectives']
lesson.video = updates_dict['video']
lesson.notes = updates_dict['notes']
lesson.auto_index = updates_dict['auto_index']
lesson.activity_title = updates_dict['activity_title']
lesson.activity_listed = updates_dict['activity_listed']
lesson.manual_progress = updates_dict['manual_progress']
activity = updates_dict.get('activity', '').strip()
errors = []
if activity:
if lesson.has_activity:
course.set_activity_content(lesson, activity, errors=errors)
else:
errors.append('Old-style activities are not supported.')
else:
lesson.has_activity = False
fs = self.app_context.fs
path = fs.impl.physical_to_logical(course.get_activity_filename(
lesson.unit_id, lesson.lesson_id))
if fs.isfile(path):
fs.delete(path)
if not errors:
common_utils.run_hooks(self.PRE_SAVE_HOOKS, lesson, updates_dict)
assert course.update_lesson(lesson)
course.save()
common_utils.run_hooks(self.POST_SAVE_HOOKS, lesson)
transforms.send_json_response(self, 200, 'Saved.')
else:
transforms.send_json_response(self, 412, '\n'.join(errors))
示例13: _import_and_validate15
def _import_and_validate15(self, unvalidated_dict, key):
errors = []
try:
question_dict = transforms.json_to_dict(
unvalidated_dict, self.get_schema().get_json_schema_dict())
except ValueError as err:
errors.append(str(err))
return (None, errors)
if not question_dict['question'].strip():
errors.append('The question must have a non-empty body.')
if not question_dict['description']:
errors.append('The description must be non-empty.')
self.validate_no_description_collision(
question_dict['description'], key, errors)
if not question_dict['graders']:
errors.append('The question must have at least one answer.')
graders = question_dict['graders']
for index in range(0, len(graders)):
grader = graders[index]
assert grader['matcher'] in [
matcher for (matcher, unused_text) in self.GRADER_TYPES]
if not grader['response'].strip():
errors.append('Answer %s has no response text.' % (index + 1))
try:
float(grader['score'])
except ValueError:
errors.append(
'Answer %s must have a numeric score.' % (index + 1))
return (question_dict, errors)
示例14: _import_and_validate15
def _import_and_validate15(self, unvalidated_dict, key):
errors = []
try:
question_dict = transforms.json_to_dict(
unvalidated_dict, self.get_schema().get_json_schema_dict())
except ValueError as err:
errors.append(str(err))
return (None, errors)
if not question_dict['question'].strip():
errors.append('The question must have a non-empty body.')
if not question_dict['description']:
errors.append('The description must be non-empty.')
self.validate_no_description_collision(
question_dict['description'], key, errors)
if not question_dict['choices']:
errors.append('The question must have at least one choice.')
choices = question_dict['choices']
for index in range(0, len(choices)):
choice = choices[index]
if not choice['text'].strip():
errors.append('Choice %s has no response text.' % (index + 1))
try:
# Coefrce the score attrib into a python float
choice['score'] = float(choice['score'])
except ValueError:
errors.append(
'Choice %s must have a numeric score.' % (index + 1))
return (question_dict, errors)
示例15: test_reject_bad_dates
def test_reject_bad_dates(self):
schema = wrap_properties({'field': {'type': 'date'}})
source = {'field': '2005/02/31'}
try:
transforms.json_to_dict(source, schema)
self.fail('Expected ValueException')
except ValueError as e:
self.assertEqual(str(e), 'day is out of range for month')
schema = wrap_properties({'field': {'type': 'date'}})
source = {'field': 'cat'}
try:
transforms.json_to_dict(source, schema)
self.fail('Expected ValueException')
except ValueError as e:
self.assertEqual(
str(e), 'time data \'cat\' does not match format \'%Y/%m/%d\'')