本文整理汇总了Python中models.transforms.dict_to_json函数的典型用法代码示例。如果您正苦于以下问题:Python dict_to_json函数的具体用法?Python dict_to_json怎么用?Python dict_to_json使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dict_to_json函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get
def get(self):
"""Handles REST GET verb and returns an object as JSON payload."""
key = self.request.get('key')
try:
entity = AnnouncementEntity.get(key)
except db.BadKeyError:
entity = None
if not entity:
transforms.send_json_response(
self, 404, 'Object not found.', {'key': key})
return
viewable = AnnouncementsRights.apply_rights(self, [entity])
if not viewable:
transforms.send_json_response(
self, 401, 'Access denied.', {'key': key})
return
entity = viewable[0]
json_payload = transforms.dict_to_json(transforms.entity_to_dict(
entity), AnnouncementsItemRESTHandler.SCHEMA_DICT)
transforms.send_json_response(
self, 200, 'Success.',
payload_dict=json_payload,
xsrf_token=XsrfTokenManager.create_xsrf_token(
'announcement-put'))
示例2: get
def get(self):
"""Handles REST GET verb and returns an object as JSON payload."""
assert is_editable_fs(self.app_context)
key = self.request.get("key")
if not FilesRights.can_view(self):
transforms.send_json_response(self, 401, "Access denied.", {"key": key})
return
# Load data if possible.
fs = self.app_context.fs.impl
filename = fs.physical_to_logical(key)
try:
stream = fs.get(filename)
except: # pylint: disable=bare-except
stream = None
if not stream:
transforms.send_json_response(self, 404, "Object not found.", {"key": key})
return
# Prepare data.
entity = {"key": key}
if self.is_text_file(key):
entity["encoding"] = self.FILE_ENCODING_TEXT
entity["content"] = vfs.stream_to_string(stream)
else:
entity["encoding"] = self.FILE_ENCODING_BINARY
entity["content"] = base64.b64encode(stream.read())
# Render JSON response.
json_payload = transforms.dict_to_json(entity, FilesItemRESTHandler.SCHEMA_DICT)
transforms.send_json_response(
self, 200, "Success.", payload_dict=json_payload, xsrf_token=XsrfTokenManager.create_xsrf_token("file-put")
)
示例3: _postprocess_rows
def _postprocess_rows(cls, unused_app_context, source_context,
schema, unused_log, unused_page_number,
rows):
transform_fn = cls._build_transform_fn(source_context)
entities = [row.for_export(transform_fn) for row in rows]
dicts = [transforms.entity_to_dict(entity) for entity in entities]
return [transforms.dict_to_json(d, schema) for d in dicts]
示例4: get
def get(self):
"""A GET REST method shared by all unit types."""
key = self.request.get('key')
if not self.can_view(self.app_context):
transforms.send_json_response(
self, 401, 'Access denied.', {'key': key})
return
course = courses.Course(self)
unit = course.find_unit_by_id(key)
if not unit:
transforms.send_json_response(
self, 404, 'Object not found.', {'key': key})
return
message = ['Success.']
if self.request.get('is_newly_created'):
unit_type = verify.UNIT_TYPE_NAMES[unit.type].lower()
message.append(
'New %s has been created and saved.' % unit_type)
entity = self.unit_to_dict(unit)
schema = self.get_schema(course, key)
schema.redact_entity_to_schema(entity, only_writable=False)
transforms.send_json_response(
self, 200, '\n'.join(message),
payload_dict=transforms.dict_to_json(entity, recurse=True),
xsrf_token=crypto.XsrfTokenManager.create_xsrf_token('put-unit'))
示例5: get
def get(self):
"""Handles REST GET verb and returns an object as JSON payload."""
key = self.request.get('key')
try:
entity = AnnouncementEntity.get(key)
except db.BadKeyError:
entity = None
if not entity:
transforms.send_json_response(
self, 404, 'Object not found.', {'key': key})
return
viewable = AnnouncementsRights.apply_rights(self, [entity])
if not viewable:
transforms.send_json_response(
self, 401, 'Access denied.', {'key': key})
return
entity = viewable[0]
schema = AnnouncementsItemRESTHandler.SCHEMA()
entity_dict = transforms.entity_to_dict(entity)
# Format the internal date object as ISO 8601 datetime, with time
# defaulting to 00:00:00
date = entity_dict['date']
date = datetime.datetime(date.year, date.month, date.day)
entity_dict['date'] = date
json_payload = transforms.dict_to_json(entity_dict)
transforms.send_json_response(
self, 200, 'Success.',
payload_dict=json_payload,
xsrf_token=crypto.XsrfTokenManager.create_xsrf_token(self.ACTION))
示例6: get
def get(self):
"""Handles REST GET verb and returns an object as JSON payload."""
key = self.request.get('key')
if not ConfigPropertyRights.can_view():
transforms.send_json_response(
self, 401, 'Access denied.', {'key': key})
return
item = None
if key and key in config.Registry.registered.keys():
item = config.Registry.registered[key]
if not item:
self.redirect('/admin?action=settings')
try:
entity = config.ConfigPropertyEntity.get_by_key_name(key)
except db.BadKeyError:
entity = None
if not entity:
transforms.send_json_response(
self, 404, 'Object not found.', {'key': key})
else:
entity_dict = {'name': key, 'is_draft': entity.is_draft}
entity_dict['value'] = transforms.string_to_value(
entity.value, item.value_type)
json_payload = transforms.dict_to_json(
entity_dict,
transforms.loads(
ConfigPropertyEditor.get_schema_json(item)))
transforms.send_json_response(
self, 200, 'Success.',
payload_dict=json_payload,
xsrf_token=XsrfTokenManager.create_xsrf_token(
'config-property-put'))
示例7: get
def get(self):
"""GET method is called when the page with the questionnaire loads."""
key = self.request.get('key')
if not self.assert_xsrf_token_or_fail(
self.request, QUESTIONNAIRE_XSRF_TOKEN_NAME, {}):
return
user = self.get_user()
if user is None:
return
student = models.Student.get_enrolled_student_by_user(user)
if student is None:
return
entity = StudentFormEntity.load_or_default(student, key)
if entity.value is None:
return
form_dict = transforms.loads(entity.value)
transforms.send_json_response(
self, 200, None,
payload_dict=transforms.dict_to_json(form_dict))
示例8: _postprocess_rows
def _postprocess_rows(cls, unused_app_context, source_context,
schema, unused_log, unused_page_number,
rows):
transform_fn = cls._build_transform_fn(source_context)
if source_context.send_uncensored_pii_data:
entities = [row.for_export_unsafe() for row in rows]
else:
entities = [row.for_export(transform_fn) for row in rows]
dicts = [transforms.entity_to_dict(entity) for entity in entities]
return [transforms.dict_to_json(d) for d in dicts]
示例9: process_get
def process_get(self):
entity = {}
schema = self.get_course().create_settings_schema()
schema.convert_entity_to_json_entity(
self.get_course_dict(), entity)
json_payload = transforms.dict_to_json(
entity, schema.get_json_schema_dict())
return json_payload
示例10: get
def get(self):
"""Handles REST GET verb and returns an object as JSON payload."""
key = self.request.get('key')
# The Entity will have been saved already either with or without data.
try:
entity = TeacherEntity.get(key)
except db.BadKeyError:
entity = None
if not entity:
transforms.send_json_response(
self, 404, 'MobileCSP: Teacher Entity not found.', {'key': key})
return
viewable = TeacherRights.apply_rights(self, [entity])
if not viewable:
transforms.send_json_response(
self, 401, 'MobileCSP: Admin access denied.', {'key': key})
return
entity = viewable[0]
schema = TeacherItemRESTHandler.SCHEMA()
entity_dict = transforms.entity_to_dict(entity)
if GLOBAL_DEBUG:
logging.warning('***RAM*** get entity = ' + str(entity_dict))
# Distinguish between adding a new entity and editing and existing entity
# If this is a new Entity, it won't have a user_id yet.
if GLOBAL_DEBUG:
logging.warning('***RAM*** user_id ' + str(entity_dict['user_id']))
if entity_dict['user_id'] or entity_dict['email'] != '':
entity_dict['mode'] = 'Edit'
else:
entity_dict['mode'] = 'Add'
# Format the internal date object as ISO 8601 datetime, with time
# defaulting to 00:00:00
date = entity_dict['date']
date = datetime.datetime(date.year, date.month, date.day)
entity_dict['date'] = date
json_payload = transforms.dict_to_json(entity_dict)
transforms.send_json_response(
self, 200, 'Success.',
payload_dict=json_payload,
xsrf_token=utils.XsrfTokenManager.create_xsrf_token(
'teacher-put'))
示例11: test_bidirectional_transforms_succeed
def test_bidirectional_transforms_succeed(self):
"""Tests that transforms entity<->dict<->json round trips correctly."""
referenced_model_key = ReferencedModel().put()
entity = UnvalidatedReference(referenced_model_key=referenced_model_key)
entity.put()
transformed = transforms.entity_to_dict(entity)
self.assertEqual(referenced_model_key, entity.referenced_model_key)
self.assertEqual(referenced_model_key, transformed["referenced_model_key"])
new_key = ReferencedModel().put()
transformed["referenced_model_key"] = new_key
restored = transforms.dict_to_entity(entity, transformed)
self.assertEqual(new_key, restored.referenced_model_key)
json = transforms.dict_to_json(transformed, None)
self.assertEqual(str(new_key), json["referenced_model_key"])
from_json = transforms.json_to_dict(json, {"properties": {"referenced_model_key": {"type": "string"}}})
self.assertEqual({"referenced_model_key": str(new_key)}, from_json)
示例12: process_get
def process_get(self):
entity = {}
schema = self.get_course().create_settings_schema()
permissions.SchemaPermissionRegistry.redact_schema_to_permitted_fields(
self.app_context, constants.SCOPE_COURSE_SETTINGS, schema)
schema.convert_entity_to_json_entity(
self.get_course_dict(), entity)
if 'homepage' in entity:
data = entity['homepage']
data['_reserved:context_path'] = self.app_context.get_slug()
data['_reserved:namespace'] = \
self.app_context.get_namespace_name()
json_payload = transforms.dict_to_json(entity)
return json_payload
示例13: _process_models_batch
def _process_models_batch(kind, cursor, batch_size, json_file):
"""Fetch and write out a batch_size number of rows using cursor query."""
query = kind.all()
if cursor:
query.with_cursor(start_cursor=cursor)
count = 0
empty = True
for model in query.fetch(limit=batch_size):
entity_dict = transforms.entity_to_dict(model, force_utf_8_encoding=True)
entity_dict["key.name"] = unicode(model.key().name())
json_file.write(transforms.dict_to_json(entity_dict, None))
count += 1
empty = False
cursor = None
if not empty:
cursor = query.cursor()
return count, cursor
示例14: get
def get(self):
"""Handles REST GET verb and returns an object as JSON payload."""
assert is_editable_fs(self.app_context)
key = self.request.get('key')
if not CourseSettingsRights.can_view(self):
transforms.send_json_response(
self, 401, 'Access denied.', {'key': key})
return
# Load data if possible.
fs = self.app_context.fs.impl
filename = fs.physical_to_logical(key)
try:
stream = fs.get(filename)
except: # pylint: disable=bare-except
stream = None
if not stream:
transforms.send_json_response(
self, 404, 'Object not found.', {'key': key})
return
# Prepare data.
entity = {}
GDefierSettingsRESTHandler.REGISTORY.convert_entity_to_json_entity(
get_course_dict(), entity)
# Render JSON response.
json_payload = transforms.dict_to_json(
entity,
GDefierSettingsRESTHandler.REGISTORY.get_json_schema_dict())
transforms.send_json_response(
self, 200, 'Success.',
payload_dict=json_payload,
xsrf_token=XsrfTokenManager.create_xsrf_token(
'basic-course-settings-put'))
示例15: get
def get(self):
"""Handles REST GET verb and returns an object as JSON payload."""
key = self.request.get('key')
try:
entity = AnnouncementEntity.get(key)
except db.BadKeyError:
entity = None
if not entity:
transforms.send_json_response(
self, 404, 'Object not found.', {'key': key})
return
viewable = AnnouncementsRights.apply_rights(self, [entity])
if not viewable:
transforms.send_json_response(
self, 401, 'Access denied.', {'key': key})
return
entity = viewable[0]
schema = AnnouncementsItemRESTHandler.SCHEMA(
'Announcement',
self.get_course().get_course_announcement_list_email())
entity_dict = transforms.entity_to_dict(entity)
entity_dict['label_groups'] = (
LabelGroupsHelper.announcement_labels_to_dict(entity))
json_payload = transforms.dict_to_json(
entity_dict, schema.get_json_schema_dict())
transforms.send_json_response(
self, 200, 'Success.',
payload_dict=json_payload,
xsrf_token=XsrfTokenManager.create_xsrf_token(
'announcement-put'))