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)
Ejemplo n.º 2
0
    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")
        )
    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'))
Ejemplo n.º 4
0
    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'))
    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'))
 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]
Ejemplo n.º 7
0
    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))
Ejemplo n.º 8
0
    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'))
Ejemplo n.º 9
0
    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'))
Ejemplo n.º 10
0
    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

        entity_dict = {'name': key, 'label': item.label}
        if entity and not entity.is_draft:
            entity_dict['value'] = transforms.string_to_value(
                entity.value, item.value_type)
        else:
            entity_dict['value'] = item.default_value
        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(
                'config-property-put'))
Ejemplo n.º 11
0
    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))
    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
 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]
Ejemplo n.º 14
0
 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]
Ejemplo n.º 15
0
    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
Ejemplo n.º 16
0
    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'))
Ejemplo n.º 17
0
    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'))
 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)
Ejemplo n.º 19
0
    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
Ejemplo n.º 20
0
    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
Ejemplo n.º 21
0
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
Ejemplo n.º 22
0
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
Ejemplo n.º 23
0
    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'))
Ejemplo n.º 24
0
    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'))
Ejemplo n.º 25
0
    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 = {}
        CourseSettingsRESTHandler.REGISTORY.convert_entity_to_json_entity(
            self.get_course_dict(), entity)

        # Render JSON response.
        json_payload = transforms.dict_to_json(
            entity, CourseSettingsRESTHandler.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'))
Ejemplo n.º 26
0
    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'))
Ejemplo n.º 27
0
    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'))
Ejemplo n.º 28
0
 def list_to_json(cls, items):
     json_dicts = [
         transforms.dict_to_json(transforms.instance_to_dict(item))
         for item in items]
     return transforms.dumps(json_dicts)
Ejemplo n.º 29
0
    def get(self):
        """Handles REST GET verb and returns an object as JSON payload."""
        key = self.request.get('key')

        try:
            entity = CourseSectionEntity.get(key)
        except db.BadKeyError:
            entity = None

        if not entity:
            transforms.send_json_response(
                self, 404, 'MobileCSP: Course Section not found.',
                {'key': key})
            return

        viewable = TeacherRights.apply_rights(self, [entity])
        if not viewable:
            transforms.send_json_response(self, 401,
                                          'MobileCSP: Access denied.',
                                          {'key': key})
            return
        entity = viewable[0]

        schema = SectionItemRESTHandler.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 an existing entity
        # If this is a new Entity, its acadyr field will be blank.
        if entity_dict['acadyr'] != '':
            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

        emails = entity_dict['students']  # Student emails are comma-delimited
        emails = emails.replace(',',
                                '\n')  # Replace with new lines for display
        entity_dict['students'] = emails

        if entity_dict['mode'] == 'Edit':
            entity_dict[
                'directions'] = "Edit a section: To add or delete students, add (or remove) their emails to (or from) the Class Roster."
        else:
            entity_dict['name'] = "New section"
            entity_dict['directions'] = "New section: Give the section a name and (optionally) a short description and pick an academic year. " + \
                "To create a roster of students, you must use the exact email that the student is registered under. Put one email per line or " + \
                "separate emails by commas."

        entity_dict.update(
            resources_display.LabelGroupsHelper.labels_to_field_data(
                common_utils.text_to_list(entity.labels)))

        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('section-put'))
Ejemplo n.º 30
0
 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]
Ejemplo n.º 31
0
def _write_model_to_json_file(json_file, privacy_transform_fn, model):
    entity_dict = _get_entity_dict(model, privacy_transform_fn)
    json_file.write(transforms.dict_to_json(entity_dict, None))
Ejemplo n.º 32
0
 def list_to_json(cls, items):
     json_dicts = [
         transforms.dict_to_json(transforms.instance_to_dict(item))
         for item in items
     ]
     return transforms.dumps(json_dicts)
Ejemplo n.º 33
0
    def get(self):
        """Handles REST GET verb and returns an object as JSON payload."""
        key = self.request.get('key')

        try:
            entity = CourseSectionEntity.get(key)
        except db.BadKeyError:
            entity = None

        if not entity:
            transforms.send_json_response(
                self, 404, 'MobileCSP: Course Section not found.', {'key': key})
            return

        viewable = TeacherRights.apply_rights(self, [entity])
        if not viewable:
            transforms.send_json_response(
                self, 401, 'MobileCSP: Access denied.', {'key': key})
            return
        entity = viewable[0]

        schema = SectionItemRESTHandler.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 an existing entity
        # If this is a new Entity, its acadyr field will be blank.
        if entity_dict['acadyr'] != '':
            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
        
        emails = entity_dict['students']   # Student emails are comma-delimited
        emails = emails.replace(',', '\n') # Replace with new lines for display
        entity_dict['students'] = emails

        if entity_dict['mode'] == 'Edit':
            entity_dict['directions'] = "Edit a section: To add or delete students, add (or remove) their emails to (or from) the Class Roster."
        else:
           entity_dict['name'] = "New section"
           entity_dict['directions'] = "New section: Give the section a name and (optionally) a short description and pick an academic year. " + \
               "To create a roster of students, you must use the exact email that the student is registered under. Put one email per line or " + \
               "separate emails by commas."

        entity_dict.update(
            resources_display.LabelGroupsHelper.labels_to_field_data(
                common_utils.text_to_list(entity.labels)))

        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(
                'section-put'))