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))
 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]
    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 format_items_for_template(self, items):
        """Formats a list of entities into template values."""
        template_items = []
        for item in items:
            item = transforms.entity_to_dict(item)

            # add 'edit' actions
            if AnnouncementsRights.can_edit(self):
                item['edit_action'] = self.get_action_url(
                    'edit', key=item['key'])

                item['delete_xsrf_token'] = self.create_xsrf_token('delete')
                item['delete_action'] = self.get_action_url(
                    'delete', key=item['key'])

            template_items.append(item)

        output = {}
        output['children'] = template_items

        # add 'add' action
        if AnnouncementsRights.can_edit(self):
            output['add_xsrf_token'] = self.create_xsrf_token('add')
            output['add_action'] = self.get_action_url('add')

        return output
 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]
Exemple #6
0
def _get_entity_dict(model, privacy_transform_fn):
    key = model.safe_key(model.key(), privacy_transform_fn)

    if privacy_transform_fn is not _IDENTITY_TRANSFORM:
        model = model.for_export(privacy_transform_fn)

    entity_dict = transforms.entity_to_dict(model, force_utf_8_encoding=True)
    entity_dict['key.name'] = unicode(key.name())
    entity_dict['key.id'] = key.id()

    return entity_dict
Exemple #7
0
    def format_dashboard_template(self, sections, user_email):
        """ Formats the template for the main Teacher Dashboard page.

            This is the page that registered teachers will see.  It consists of
            list of the teacher's course sections and buttons to manage the
            sections. 
        """
        template_sections = []
        if sections:
            for section in sections:
                section = transforms.entity_to_dict(section)
                date = section.get('date')
                if date:
                    date = datetime.datetime.combine(
                        date, datetime.time(0, 0, 0, 0))
                    section['date'] = (
                        date - datetime.datetime(1970, 1, 1)).total_seconds() * 1000

                if GLOBAL_DEBUG:
                    logging.debug('***RAM*** format template section = ' + str(section))

                # Add 'edit' and 'delete' actions to each section that will be displayed

                if section['teacher_email'] == user_email and TeacherRights.can_edit_section(self):
                    section['edit_action'] = self.get_dashboard_action_url(
                        TeacherDashboardHandler.EDIT_SECTION_ACTION, key=section['key'])

                    section['delete_xsrf_token'] = self.create_xsrf_token(
                        TeacherDashboardHandler.DELETE_SECTION_ACTION)
                    section['delete_action'] = self.get_dashboard_action_url(
                        TeacherDashboardHandler.DELETE_SECTION_ACTION,
                        key=section['key'])
                    template_sections.append(section) 

        output = {}
        output['sections'] = template_sections

        # Add actions for the 'New Section' button
        output['newsection_xsrf_token'] = self.create_xsrf_token(
            TeacherDashboardHandler.ADD_SECTION_ACTION)
        output['add_section'] = self.get_dashboard_action_url(
            TeacherDashboardHandler.ADD_SECTION_ACTION)

        # Add actions of the 'Admin' button -- to add new teachers
        if TeacherRights.can_edit(self):
            output['is_admin'] = True
            output['add_xsrf_token'] = self.create_xsrf_token(
                AdminDashboardHandler.ADMIN_LIST_ACTION)
            output['add_action'] = self.get_admin_action_url(
                AdminDashboardHandler.ADMIN_LIST_ACTION)
        return output
    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)
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
Exemple #11
0
    def format_admin_template(self, items):
        """ Formats the template for the Admin 'Add Teacher' page.

            When clicked the 'Admin: Add Teacher button opens up 
            a list of teachers plus and 'Add Teacher' button.
        """
        template_items = []
        for item in items:
            item = transforms.entity_to_dict(item)
            date = item.get('date')
            if date:
                date = datetime.datetime.combine(
                    date, datetime.time(0, 0, 0, 0))
                item['date'] = (
                    date - datetime.datetime(1970, 1, 1)).total_seconds() * 1000

            # add 'edit' actions
            if TeacherRights.can_edit_section(self):
                item['edit_action'] = self.get_admin_action_url(
                     AdminDashboardHandler.ADMIN_EDIT_ACTION, key=item['key'])
                item['delete_xsrf_token'] = self.create_xsrf_token(
                    AdminDashboardHandler.ADMIN_DELETE_ACTION)
                item['delete_action'] = self.get_admin_action_url(
                    AdminDashboardHandler.ADMIN_DELETE_ACTION,
                    key=item['key'])

            template_items.append(item)

        output = {}
        output['children'] = template_items

        # Add actions for the 'Add Teacher'
        if TeacherRights.can_edit(self):
            output['add_xsrf_token'] = self.create_xsrf_token(
                AdminDashboardHandler.ADMIN_ADD_ACTION)
            output['add_action'] = self.get_admin_action_url(
                AdminDashboardHandler.ADMIN_ADD_ACTION)

        return output
Exemple #12
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'))
    def format_items_for_template(self, items):
        """Formats a list of entities into template values."""
        template_items = []
        for item in items:
            item = transforms.entity_to_dict(item)

            # add 'edit' actions
            if AnnouncementsRights.can_edit(self):
                item["edit_action"] = self.get_action_url("edit", item["key"])

                item["delete_xsrf_token"] = self.create_xsrf_token("delete")
                item["delete_action"] = self.get_action_url("delete", item["key"])

            template_items.append(item)

        output = {}
        output["children"] = template_items

        # add 'add' action
        if AnnouncementsRights.can_edit(self):
            output["add_xsrf_token"] = self.create_xsrf_token("add")
            output["add_action"] = self.get_action_url("add")

        return output
    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'))
    def format_items_for_template(self, items):
        """Formats a list of entities into template values."""
        template_items = []
        for item in items:
            item = transforms.entity_to_dict(item)
            date = item.get('date')
            if date:
                date = datetime.datetime.combine(
                    date, datetime.time(0, 0, 0, 0))
                item['date'] = (
                    date - datetime.datetime(1970, 1, 1)).total_seconds() * 1000

            # add 'edit' actions
            if AnnouncementsRights.can_edit(self):
                item['edit_action'] = self.get_announcement_action_url(
                    AnnouncementsDashboardHandler.EDIT_ACTION, key=item['key'])

                item['delete_xsrf_token'] = self.create_xsrf_token(
                    AnnouncementsDashboardHandler.DELETE_ACTION)
                item['delete_action'] = self.get_announcement_action_url(
                    AnnouncementsDashboardHandler.DELETE_ACTION,
                    key=item['key'])

            template_items.append(item)

        output = {}
        output['children'] = template_items

        # add 'add' action
        if AnnouncementsRights.can_edit(self):
            output['add_xsrf_token'] = self.create_xsrf_token(
                AnnouncementsDashboardHandler.ADD_ACTION)
            output['add_action'] = self.get_announcement_action_url(
                AnnouncementsDashboardHandler.ADD_ACTION)

        return output
 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]
Exemple #17
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'))
Exemple #18
0
 def get_data_dict(cls, course, key):
     entity = cls.get_resource(course, key)
     return transforms.entity_to_dict(entity)
    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'))