def post(self, subject_id):

        logging.info("INTO DELETESUBJECTTREE HANDLER!!")

        to_be_deleted = Subject.get_by_id(int(subject_id))
        deleted_name = to_be_deleted.name
        to_be_deleted.deleteSubjectRecursive()

        self.render_json({"msg": "成功刪除科目%s, 還有一切以下的子科目。" % deleted_name})
        return
    def get(self):

        user = UserData.get_current_user()
        if not user.is_server_admin():
            self.redirect('find-resource')

        root_subjects = Subject.getSubjectByLevel(0)
        data = {
            'root_subjects': root_subjects
        }

        self.render('admin/upload-subject-tree.html', data)
    def post(self):

        def append_node_to_tree(node_list, tree):  # tree is empty list at first
            cursor = tree
            for index, value in enumerate(node_list):
                if value in [c['name'] for c in cursor]:
                    cursor = cursor[[c['name'] for c in cursor].index(value)]['children']
                else:
                    if index+1 != len(node_list):
                        cursor.append({'name': value, 'children': []})
                        cursor = cursor[-1]['children']
                    else:
                        cursor.append({'name': value})

        user = UserData.get_current_user()
        if not user.is_server_admin():
            self.redirect('find-resource')

        csv_file = self.request.get("subject-tree-csv")
        logging.info('csv file : %s' % csv_file)

        tree = []
        if csv_file:
            for line in csv_file.splitlines():
                append_node_to_tree(line.split(','), tree)

        logging.info("tree: %s" % tree)
        if len(tree) > 1:
            self.render_json({"error": "系統目前不支援同時上傳多個科目,換句話說,您上傳的csv的第一行名稱需要全部相同。"})
            return

        root_subject = Subject.buildSubjectTree(tree[0])
        tree[0]['root_subject_id'] = root_subject.key.id()
        self.render_json(tree[0])

        return
    def __call__(self, environ, start_response):
    
        # SQLAlchemy boilerplate code to connect to db and connect models to db objects
        engine = create_engine(engine_string)
        Session = sessionmaker(bind=engine)
        session = Session()

        req = Request(environ)

        if req.method != 'POST':
            resp = HTTPBadRequest('This page can only be accesses via POST')
            return resp(environ, start_response)
        else:
            firstname = req.POST['firstname']
            lastname = req.POST['lastname']
            subj = Subject(firstname=firstname, lastname=lastname)

            to_add = {}
            for k in ('amerind', 'afram', 'pacif', 'asian', 'white',
                      'unknown', 'ur_student', 'hearing_normal', 'more_expts'):
                if req.POST.has_key(k):
                    to_add[k] = True

            for k in ('sex', 'ethnicity', 'other_race', 'gradyear',
                      'hearing_problems', 'vision_normal', 'vision_other'):
                if req.POST.has_key(k):
                    if req.POST[k] not in (None, '', u''):
                        to_add[k] = req.POST[k]

            if req.POST.has_key('age'):
                if req.POST['age'] not in (None, ''):
                    to_add['age'] = int(req.POST['age'])

            if req.POST['entrydate'] not in (None, '', u''):
                to_add['entrydate'] = parser.parse(req.POST['entrydate']).date()
            else:
                to_add['entrydate'] = date.today()

            subj.from_dict(to_add)
            try:
                session.add(subj)
                session.commit()
            except IntegrityError as e:
                resp = HTTPBadRequest(e)
                return resp(environ, start_response)

            if req.POST.has_key('phone'):
                if req.POST['phone'] not in (None, '', u''):
                    p = Phone(subject = subj, number = req.POST['phone'])
                    session.add(p)
                    session.commit()

            if req.POST.has_key('email'):
                if req.POST['email'] not in (None, '', u''):
                    em = Email(subject = subj, address = req.POST['email'])
                    session.add(em)
                    session.commit()

            from pprint import pformat
            #output = pformat(subj.to_dict(deep={'phone': {}, 'email': {}}))
            env = Environment(loader=FileSystemLoader(os.path.join(basepath,'templates')))
            template = env.get_template('subject_list.html')
            template = template.render(subjects = [subj.to_dict(deep={'phone': {}, 'email': {}}),])

            resp = Response()
            resp.content_type='text/html'
            resp.unicode_body = template
            #resp.content_type='text/plain'
            #resp.body = output
            return resp(environ, start_response)