def insert_item(argv):
    '''Takes the system arguments as parameter and then inserts the item.

    Keyword arguments:
    argv -- An array of command line arguments passed to the program.
    '''
    if argv[2] == "school":
        school = School.create(name=argv[3])
        print "New school: " + str(School.get(School.name == argv[3]))
    elif argv[2] == "batch":
        batch = Batch.create(school=argv[3], name=argv[4])
        print "New batch: " + str(Batch.get(Batch.name == argv[4]))
    elif argv[2] == "student":
        print "New student:",
        if len(argv) > 6:
            student = Student.create(batch=argv[3],
                                     age=argv[4],
                                     last_name=argv[5],
                                     first_name=argv[6])
            print str(Student.get(Student.age == argv[4] and
                                  Student.last_name == argv[5] and
                                  Student.first_name == argv[6]))
        else:
            student = Student.create(batch=argv[3],
                                     age=argv[4],
                                     last_name=argv[5])
            print str(Student.get(Student.age == argv[4] and
                                  Student.last_name == argv[5]))
    elif argv[2] == "exercise":
        exercise = Exercise.create(student=argv[3],
                                   subject=argv[4],
                                   note=argv[5])
        print "New Exercise: " + str(exercise)
示例#2
0
 def post(self, username=""):
     user = self.getCookieCacheUser()
     class_name = self.request.get("class-name")
     class_instructor = self.request.get("class-instructor")
     class_year = self.request.get("year")
     school_id = self.request.get("school_id")
     school = School.get_by_id(int(school_id))
     if class_name and class_instructor and class_year and school:
         new_class = Class(name=class_name,
                           school=school,
                           instructor=class_instructor,
                           year=int(class_year),
                           user_creator=user,
                           requests=[])
         new_class.other_users.append(str(user.key().id()))
         new_class.put()
         memcache.set(str(user.key().id()) + class_name, new_class)
         memcache.delete(str(user.key().id()))
         self.redirect("/%s/%s" % (user.username, new_class.name))
     else:
         schools = School.all()
         self.render("create-class.html",
                     schools=schools,
                     class_name=class_name,
                     class_instructor=class_instructor,
                     year=class_year,
                     class_active="active")
示例#3
0
def create_school():
    name = input('学校名字: ').strip()
    addr = input('学校地址: ').strip()
    school_list = [(obj.name, obj.addr)
                   for obj in School.get_obj_list()]  # 学校列表
    if (name, addr) in school_list:
        print('\033[31;1m学校名 [%s], 学校地址[%s] 已存在\033[0m' % (name, addr))
    else:
        school = School(name, addr)
        school.save()
        print('\033[33;1m学校[%s], 地址[%s] 创建成功\033[0m' % (name, addr))
def school2db(response):
    reader = csv.DictReader(StringIO(response.read().decode()))
    for row in reader:
        if row['LGA']:
            lga_name = ''.join(x.lower() for x in row['LGA'] if x.isalpha())
            school_name = row['School_name']
            post_code = str(row['Postcode'])
            latitude = str(row['Latitude'])
            longitude = str(row['Longitude'])
            school_type = str(row['Level_of_schooling'])
            school = School(lga_name, school_name, post_code, latitude, longitude, school_type)
            school.save()
示例#5
0
 def post(self, request):
     """
     Create school record in database
     :param request: Key value pair data
     :return: status & respective message
     """
     data = request.data
     try:
         school = School(**data)
         school.save()
         LOGGER.info("School created successfully")
     except Exception, error:
         LOGGER.error("Error:%s", str(error))
         return Response({"status": "FAILED", "message": str(error)})
示例#6
0
def submit():
    d = request.json
    for (k, v) in d.items():
        print(f'{k} : {v}')

    # s = Student(email=d['email'],childName=d['childName'], atVenue = d['atVenue'], accommodation_other = d['accommodation_other'], twin = d['twin'],rankings=d['rankings'],schoolId=d['schoolId'],hebSchoolId=d['hebSchoolId'],school=d['school'],hebSchool=d['hebSchool'],DOB=d['DOB'])
    s = Student(**d)
    db.session.add(s)
    # db.session.flush()
    # db.session.refresh(s)
    db.session.commit()
    # db.session.add(s)
    nonDates = d['nonDates']
    for nonDate in nonDates:
        greg = nonDate['greg']
        gdate = date(greg['year'], greg['month'], greg['day'])
        nd = NonDate(greg=gdate)
        nd.hdate_str = nonDate['hdate_str']
        nd.hdate_str_heb = nonDate['hdate_str_heb']
        nd.student_id = s.id
        s.nonDates.append(nd)
        nd.student = s
        print("APPENDING non-DATE")
        print(f"student_id is: {s.id}")
        db.session.add(nd)

    sch = School.query.filter_by(id=d['schoolId']).first()
    if sch is None:
        sch = School()
        sch.name = d['school']
        db.session.add(sch)
        db.session.commit()
        sch.students.append(s)
    else:
        sch.students.append(s)
    hSch = HebSchool.query.filter_by(id=d['hebSchoolId']).first()
    if hSch is None:
        hSch = HebSchool()
        hSch.name = d['hebSchool']
        db.session.add(hSch)
        hSch.students.append(s)
    else:
        hSch.students.append(s)
    db.session.commit()
    q.enqueue_call(func=send_submission_email,
                   kwargs={'student_id': s.id},
                   result_ttl=5000)
    return jsonify({"resp": "good!"}), 200
示例#7
0
def register():
    form: RegisterForm = RegisterForm(request.form)

    if request.method == "POST" and form.validate_on_submit():
        username: str = form.username.data
        password: str = form.password.data
        password_confirm: str = form.password_confirm.data
        school_name: str = form.school.data

        if password != password_confirm:
            return render_template("forms/register.html",
                                   form=form,
                                   error="비밀번호를 다시 입력해주세요.")

        if User.query.filter(User.username == username).first() is not None:
            return render_template("forms/register.html",
                                   form=form,
                                   error="중복되는 아이디입니다.")

        school: School = School.query.filter(
            School.name == school_name).first()

        if school is None:
            school = School.generate(db_session, school_name)

        db_session.add(
            User(username=username,
                 password=authenticator.hash(password),
                 school=school)), db_session.commit()

        return redirect("/login")

    return render_template("forms/register.html", form=form)
示例#8
0
    def setUp(self):
        self.school = School(name='Minnesota')
        db.session.add(self.school)
        db.session.commit()

        self.tch = Teacher(first_name='Jess',
                           last_name='Christensen',
                           title='K4-2nd Sped',
                           school_id=self.school.id,
                           username='******',
                           password='******')
        db.session.add(self.tch)
        db.session.commit()

        self.stu = Student(first_name='Fake',
                           last_name='Kid',
                           dob=date(2012, 1, 24),
                           grade=1,
                           teacher_id=self.tch.id,
                           dis_area='OHI')
        db.session.add(self.stu)
        db.session.commit()

        self.iep = IEP(student_id=self.stu.id, teacher_id=self.tch.id)

        db.session.add(self.iep)
        db.session.commit()
示例#9
0
def get_or_create_school(db, id):
    school = db.query(School).get(id)
    if school is None:
        school = School(id=id)
        db.add(school)
        db.commit()
    return school
示例#10
0
def flush():
    ndb.delete_multi(School.query().fetch(keys_only=True))
    ndb.delete_multi(QuestionInstance.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Question.query().fetch(keys_only=True))
    ndb.delete_multi(State.query().fetch(keys_only=True))
    ndb.delete_multi(Address.query().fetch(keys_only=True))
    ndb.delete_multi(Teacher.query().fetch(keys_only=True))
    ndb.delete_multi(Class.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(Student.query().fetch(keys_only=True))
    ndb.delete_multi(UserInfo.query().fetch(keys_only=True))
    ndb.delete
    _multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment.query().fetch(keys_only=True))
    ndb.delete_multi(Subject.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Subject_Topics.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Topic.query().fetch(keys_only=True))
    ndb.delete_multi(User.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(State_Types.query().fetch(keys_only=True))
示例#11
0
def flush():
    ndb.delete_multi(School.query().fetch(keys_only=True))
    ndb.delete_multi(QuestionInstance.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Question.query().fetch(keys_only=True))
    ndb.delete_multi(State.query().fetch(keys_only=True))
    ndb.delete_multi(Address.query().fetch(keys_only=True))
    ndb.delete_multi(Teacher.query().fetch(keys_only=True))
    ndb.delete_multi(Class.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(Student.query().fetch(keys_only=True))
    ndb.delete_multi(UserInfo.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment.query().fetch(keys_only=True))
    ndb.delete_multi(Subject.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(State_Questions.query().fetch(keys_only=True))
    ndb.delete_multi(Topic_States.query().fetch(keys_only=True))
    ndb.delete_multi(Subject_Topics.query().fetch(keys_only=True))
    ndb.delete_multi(Student_Assessments.query().fetch(keys_only=True))
    ndb.delete_multi(Topic.query().fetch(keys_only=True))
    ndb.delete_multi(User.query().fetch(keys_only=True))
    ndb.delete_multi(Assessment_Record.query().fetch(keys_only=True))
    ndb.delete_multi(State_Types.query().fetch(keys_only=True))
示例#12
0
def create_course():
    try:
        print('创建课程'.center(60, '-'))
        school_list = School.get_all_obj_list()
        for k, obj in enumerate(school_list):
            print(k, obj, obj.addr)
        sid = int(input('请选择学校:'))
        school_obj = school_list[sid]

        name = input('请输入课程名:').strip()
        price = input('请输入课程价格:').strip()
        period = input('请输入课程周期:').strip()

        course_name_list = [(obj.name, obj.school_nid.uuid)
                            for obj in Course.get_all_obj_list()]
        if (name, school_obj.nid.uuid) in course_name_list:
            raise Exception('\033[43;1m课程[%s] 已存在,不可重复创建\033[0m' % name)
        obj = Course(name, price, period, school_obj.nid)
        obj.save()
        status = True
        error = ''
        data = '\033[33;1m课程[%s] 价格[%s] 周期[%s] 创建成功\033[0m' % (
            obj.name, obj.price, obj.period)
    except Exception as e:
        status = False
        error = str(e)
        data = ''
    return {'status': status, 'error': error, 'data': data}
示例#13
0
    def setUp(self):

        School.query.delete()
        Teacher.query.delete()

        self.client = app.test_client()

        self.school = School(name='Minnesota')

        db.session.add(self.school)
        db.session.commit()

        self.teacher = Teacher(first_name='Maria',
                               last_name='Aldapa',
                               title='Teacher',
                               school_id=self.school.id,
                               username='******',
                               password='******')

        self.data = {
            'first_name': self.teacher.first_name,
            'last_name': self.teacher.last_name,
            'title': self.teacher.title,
            'school_id': self.teacher.school_id,
            'username': self.teacher.username,
            'password': self.teacher.password,
            'confirm': self.teacher.password
        }
示例#14
0
def delete_school(id):
    # Get school from db or 404
    school = School.get_or_404(id)
    if request.method == 'POST':
        school.delete()
        flash('School successfully deleted')
        return redirect(url_for('view_all_schools'))
    return render_template('delete_school.html', school=school)
示例#15
0
def edit_course(id):
    # Get course from db or 404
    course = Course.get_or_404(id)
    # Start with no errors
    errors = None
    # Get categories and schools to populate dropdowns
    categories = Category.get_all()
    schools = School.get_all()

    if request.method == 'POST':
        fields = {
            'name': request.form['name'],
            'url': request.form['url'],
            'school': request.form.get('school', ''),
            'category': request.form.get('category', '')
        }
        # Validations that checks that no fields are blank
        errors = check_no_blanks(fields=fields)
        if not errors:
            # Check that new course name does not exist already for this school
            school_courses = School.get_by_id(fields['school']).courses
            for school_course in school_courses:
                # If name isn't changed, will exist so allow this
                if school_course.name == fields['name'] and \
                        school_course.id != course.id:
                    errors['name_exists'] = True
            if not errors:
                course.edit(name=fields['name'],
                            url=fields['url'],
                            school_id=fields['school'],
                            category_id=fields['category'])
                flash('Course edited')
                return redirect(url_for('view_course', id=course.id))
    # If it is not a POST request, populate input values from database
    else:
        fields = {
            'name': course.name,
            'url': course.url,
            'school': course.school.id,
            'category': course.category.id
        }
    return render_template('edit_course.html',
                           fields=fields,
                           errors=errors,
                           categories=categories,
                           schools=schools)
示例#16
0
 def get(self):
     self.response.out.write('processing data<br>')
     
     datapath = os.path.join(os.path.dirname(__file__), 'data.csv')
     
     logging.info(datapath)
     
     datafile = codecs.open(datapath, 'r', 'iso-8859-15')
     
     for line in datafile.readlines():
         parts = line.split(';')
         
         logging.debug(parts)
         
         school = School()
         school.brin = parts[0].strip()[1:-1]
         school.name = parts[1].strip()[1:-1]
         school.slug = slugify(school.name)
         
         school.put()
         
         logging.info('created school ' + str(school.key().id()))
         
         self.response.out.write('%s %s %s <br>' % (school.brin, school.name, school.slug))
     datafile.close()
示例#17
0
 def get(self, username=""):
     user = self.getCookieCacheUser()
     if username == user.username:
         schools = School.all()
         self.render("create-class.html",
                     current_user=user,
                     schools=schools,
                     page_title="Create New Class",
                     class_active="active")
示例#18
0
def get_all_schools():
    schools = School.objects()
    response = []
    for school in schools:
        temp = {}
        for key in school:
            temp[key] = school[key]
        response.append(temp)
    return jsonify(response), 200
示例#19
0
def get_school(code):
    schools = School.objects(code=code)
    if len(schools) == 0:
        return jsonify(message='No school found'), 404
    response = {}
    school = schools.first()
    for key in school:
        response[key] = school[key]
    return jsonify(response), 200
示例#20
0
def school_list(level):
    search = False
    temp_level = level
    if level == 'special':
        temp_level = 'specific'
    query = request.args.get('query')
    if query:
        search = True
        schools = School.objects(level__icontains=temp_level, name__icontains=query)
    else:
        schools = School.objects(level__icontains=temp_level)
    schools = schools.order_by('-enrolments')
    page, per_page, offset = get_page_args()
    per_page *= 5
    offset *= 5
    pagination_schools = schools[offset: offset + per_page]
    pagination = Pagination(page=page, per_page=per_page, total=schools.count(), record_name="schools",
                            css_framework="bootstrap4", alignment="center", search=search, found=schools.count())
    return render_template("school_list.html", schools=pagination_schools, level=level, pagination=pagination)
def print_student_by_school(argv):
    '''Takes the system arguments as parameter and then prints the students
    based on the student id. Prints 'School not found' if the id does not
    exist.

    Keyword arguments:
    argv -- An array of command line arguments passed to the program.
    '''
    i = 0
    # for student in Student.select().where(Student.school.id == argv[2]):
    for student in Student.select():
        if str(student.batch.school.id) == str(argv[2]):
            print student
    for item in School.select():
        if str(item.id) == str(argv[2]):
            break
        i += 1
    if i == len(School.select()):
        print "School not found"
示例#22
0
def create_school():
    try:
        name = input('请输入学校名字:').strip()
        addr = input('请输入学校地址:').strip()
        school_name_list = [(obj.name, obj.addr)
                            for obj in School.get_all_obj_list()]
        if (name, addr) in school_name_list:
            raise Exception(
                '\033[43;1m[%s] [%s]校区已经存在,不可重复创建,你有那么多学生吗?\033[0m' %
                (name, addr))
        obj = School(name, addr)
        obj.save()
        status = True
        error = ''
        data = '\033[33;1m[%s] [%s]校区创建成功\033[0m' % (obj.name, obj.addr)
    except Exception as e:
        status = False
        error = str(e)
        data = ''
    return {'status': status, 'error': error, 'data': data}
示例#23
0
 def read_data(self):
     with open(SCHOOLS_FILE, encoding='ISO-8859-1') as csvfile:
         rows_reader = csv.reader(csvfile, delimiter=',')
         next(rows_reader)
         schools = []
         for row in rows_reader:
             state = 'DC' if row[5] == 'C' else row[5]
             school = School(row[0], row[3], row[2], row[4], state, row[8],
                             row[9])
             schools.append(school)
     return schools
示例#24
0
def add_course():
    # Start with no errors and no fields
    errors = None
    fields = None
    # Grab user id. Associates course with user.
    user_id = session['user_id']
    # Get all categories and schools to populate dropdowns
    categories = Category.get_all()
    schools = School.get_all()

    if request.method == 'POST':
        # Grab all form data
        fields = {
            'name': request.form['name'],
            'url': request.form['url'],
            'school': request.form.get('school', ''),
            'category': request.form.get('category', '')
        }
        # Form validation that makes sure no fields are blank
        errors = check_no_blanks(fields=fields)
        if not errors:
            # Check if school already has course by same name
            school_courses = School.get_by_id(fields['school']).courses
            for school_course in school_courses:
                if school_course.name == fields['name']:
                    errors['name_exists'] = True
            # If there are no errors, then create course
            if not errors:
                course = Course.create(name=fields['name'],
                                       url=fields['url'],
                                       school_id=fields['school'],
                                       category_id=fields['category'],
                                       user_id=user_id)
                flash('Course created')
                return redirect(url_for('view_course', id=course.id))
    # If this is a GET request, or there are errors, show form
    return render_template('add_course.html',
                           fields=fields,
                           categories=categories,
                           schools=schools,
                           errors=errors)
示例#25
0
    def test_children_ask_for_leave_list(self):
      
        sch = School(school_name="_name1", classes_number=100)
        sch.save()

        twz = Classes(class_name="WeizhongTu", children_number=100,schoolkey=sch)
        twz.save()

        children = Children()
        children.Classeskey = twz
        children.nicename = "1"
        children.save() 
   
        children2 = Children()
        children2.Classeskey = twz
        children2.nicename = "2"
        children2.stats= "路途中"
        children2.save() 

        children3 = Children()
        children3.Classeskey = twz
        children3.nicename = "3"
        children3.stats= "已到达"
        children3.save() 

        leave = Children_ask_for_leave()
        leave.begin_time = datetime.datetime.now() - datetime.timedelta(hours=10)
        leave.end_time = datetime.datetime.now() + datetime.timedelta(hours=10)
        leave.Childrenkey_id = 1 
        leave.save()
        print(leave.begin_time)
        print(datetime.datetime.now())
        print(leave.end_time)


        classes = Classes.objects.get(pk=1)
        list = classes.children_ask_for_leave_list()
        list2 = classes.children_arrived_list()
        list3 = classes.children_road_list()
        count = list.count()+list2.count()+list3.count()
        self.assertEqual(list.count(), 1)
示例#26
0
def schools(request):
    """ Ajax: School autcomplete form field """
    if request.is_ajax() and request.method == 'POST' and request.POST.has_key('q'):
        query = request.POST.get('q')
        schools = School.objects.filter(name__icontains=query).distinct()
        response = {}
        if len(schools) > 0:
            response['schools'] = [(school.pk, school.name) for school in schools]
            response['status'] = 'success'
        return HttpResponse(json.dumps(response), mimetype="application/json")
    elif request.method == 'POST':
        # for creating a new school from a form
        # create new school, hasn't been implemented yet
        new_school = School()
        a_school = UsdeSchool.objects.get(id=request.POST['school_id'])
        new_school.name = a_school.institution_name
        new_school.location = u"%s, %s" % (a_school.institution_city, a_school.institution_state)
        new_school.url = a_school.institution_web_address
        new_school.save()
        request.user.get_profile().school = new_school
        request.user.get_profile().save()

        response = {}
        return HttpResponse(json.dumps(response), mimetype="application/json")
    else:
        # render the browse-schools route
        response = {}
        response['schools'] = School.objects.order_by('-karma').all()
        return render(request, 'n_browse_schools.html', response)


    raise Http404
def get_all_school_data():
    qs = School.objects()
    entries = []
    for school in qs:
        entries.append({'school_name': school.school_name,
                        'lga_name': school.lga_name,
                        'post_code': school.post_code,
                        'latitude': school.latitude,
                        'longitude': school.longitude,
                        'school_type': school.school_type})
    return jsonify(title='NSW School Data',
                   id=request.base_url,
                   entry=entries), 200
示例#28
0
def create_course():
    school_list = School.get_obj_list()  # 所有学校列表
    for k, obj in enumerate(school_list):
        print(k, obj.name, obj.addr)
    choose = input('选择学校 >> ').strip()
    if choose.isdigit():
        choose = int(choose)
        if choose < len(School.get_obj_list()):
            choose_school = school_list[choose]  # 选择的学校
            name = input('课程名 >> ').strip()
            period = input('课程周期(month) >> ').strip()
            price = input('课程价格(RMB) >> ').strip()

            course_list = [obj.name for obj in Course.get_obj_list()]
            if name in course_list:
                print('\033[33;1m课程[%s]已存在\033[0m' % name)
            else:
                course = Course(name, price, period, choose_school.nid)
                course.save()
                print('\033[33;1m课程[%s]创建成功\033[0m' % name)
        else:
            print('请正确输入')
示例#29
0
def school(request, school_query):
    """ View for a school, lists courses and school activity
        :school_query: comes as unicode, if can be int, pass as int
    """
    response = {}
    try:
        school_query = int(school_query)
    except ValueError:
        # cant be cast as an int, so we will search for it as a string
        pass
    # FIXME: does this work _instead_ or despite of int() casting?
    response['school'], response['courses'] = School.get_courses(school_query)
    return render(request, 'n_school.html', response)
示例#30
0
def compare_schools():
    codes = request.args.getlist('code')
    if len(codes) == 0:
        return jsonify(message='No input'), 204
    schools = School.objects(code__in=codes)
    if len(schools) == 0:
        return jsonify(message='No schools found matching the codes'), 404
    response = []
    for school in schools:
        temp = {}
        for key in school:
            temp[key] = school[key]
        response.append(temp)
    return jsonify(response), 200
示例#31
0
def edit_school(id):
    # Get school from db or 404
    school = School.get_or_404(id)
    # Start with no errors
    errors = None
    if request.method == 'POST':
        fields = {'name': request.form['name'], 'url': request.form['url']}
        # Validations that check that no fields are empty
        errors = check_no_blanks(fields=fields)
        if not errors:
            # Check that school name does not match other school names,
            # except if it is the same instance
            if (School.get_by_name(fields['name'])
                    and School.get_by_name(fields['name']).id != school.id):
                errors['name_exists'] = True
            if not errors:
                school.edit(name=fields['name'], url=fields['url'])
                flash('School edited')
                return redirect(url_for('view_school', id=school.id))
    # If it is not a POST rquest, populate field values from database
    else:
        fields = {'name': school.name, 'url': school.url}
    return render_template('edit_school.html', fields=fields, errors=errors)
示例#32
0
def add_school():
    # Start with no errors and no fields
    errors = None
    fields = None
    # Store user id from session to associate school with user
    user_id = session['user_id']

    if request.method == 'POST':
        fields = {'name': request.form['name'], 'url': request.form['url']}
        # Validate form submission by checking no empty fields
        errors = check_no_blanks(fields=fields)
        if not errors:
            # Check that school name does not already exist
            # TODO: this check needs to check by case insensitive
            if School.get_by_name(fields['name']):
                errors['name_exists'] = True
            else:
                school = School.create(name=fields['name'],
                                       url=fields['url'],
                                       user_id=user_id)
                flash('School created')
                return redirect(url_for('view_school', id=school.id))
    return render_template('add_school.html', fields=fields, errors=errors)
def export_json(argv):
    '''Export all data in JSON format.

    Keyword arguments:
    argv -- An array of command line arguments.
    '''
    data = []
    for school in School.select():
        dict = {"name": school.name}
        data.append(dict)

    '''Add the batches.'''
    for dict in data:
        batches = []
        for batch in Batch.select():
            if batch.school.name == dict["name"]:
                batch_dict = {}
                dict["batches"] = batches
                batch_dict["name"] = batch.name
                batches.append(batch_dict)

    '''Add the students in their batch.'''
    for dict in data:
        if dict.get("batches") is not None:
            for batch in dict.get("batches"):
                students = []
                for student in Student.select():
                    if str(student.batch.name) == str(batch["name"]):
                        student_dict = {}
                        batch["students"] = students
                        student_dict["first_name"] = student.first_name
                        student_dict["last_name"] = student.last_name
                        student_dict["age"] = student.age
                        students.append(student_dict)

    '''Add the exercises to the corresponding student.'''
    for dict in data:
        if dict.get("batches") is not None:
            for batch in dict.get("batches"):
                for student in batch["students"]:
                    exercises = []
                    for e in Exercise.select():
                        if e.student.first_name == student.get("first_name"):
                            exercsie_dict = {}
                            student["exercises"] = exercises
                            exercsie_dict["note"] = e.note
                            exercsie_dict["subject"] = e.subject
                            exercises.append(exercsie_dict)

    print json.dumps(data)
示例#34
0
def create_classes():
    school_list = School.get_obj_list()  # 所有学校列表
    for k, obj in enumerate(school_list):
        print(k, '学校:[%s]  地址:[%s]' % (obj.name, obj.addr))
    choose = input('选择学校 >> ').strip()
    if choose.isdigit():
        choose = int(choose)
        if choose < len(School.get_obj_list()):
            choose_school = school_list[choose]  # 选择的学校
            name = input('请输入班级名字 >> ')
            classes_list = [obj.name for obj in Classes.get_obj_list()]
            if name in classes_list:
                print('\033[31;1m班级[%s] 已存在\033[0m' % name)
            else:
                course_teacher_list = Course_teacher.get_obj_list()
                for j, ct in enumerate(course_teacher_list):
                    print(j,
                          ct.course_id.get_obj_uuid().name,
                          ct.teacher_id.get_obj_uuid().name)
                choose_course_teacher = input('选择关联的课程讲师 >> ').strip()
                choose_ct_id = course_teacher_list[int(choose_course_teacher)]
                classes = Classes(name, choose_school.nid, choose_ct_id.nid)
                classes.save()
                print('\033[32;1m班级[%s] 创建成功\033[0m' % name)
示例#35
0
def populate():
    # from models import School,HebSchool
    names = ['Lainer School']
    for name in names:
        school = School.query.filter_by(name=name).first()
        if school is None:
            school = School(name=name)
        db.session.add(school)
    db.session.commit()
    hNames = ["Temple Isaiah"]
    for name in hNames:
        school = HebSchool.query.filter_by(name=name).first()
        if school is None:
            school = HebSchool(name=name)
        db.session.add(school)
    db.session.commit()
def get_school_data_by_lga(lga_name):
    qs = School.objects(lga_name=lga_name)
    entries = []
    if qs.count() != 0:
        for school in qs:
            entries.append({'school_name': school.school_name,
                            'post_code': school.post_code,
                            'latitude': school.latitude,
                            'longitude': school.longitude,
                            'school_type': school.school_type})
        return jsonify(title='School Data in {} Local Government Area'.format(lga_name),
                       lga_name=lga_name,
                       id=request.base_url,
                       entry=entries), 200
    else:
        return "LGA name not found.", 404
示例#37
0
文件: views.py 项目: mpevner/djKarma
def browse_courses(request, school_query):
    """ View for courses beloging to :school_query:
        :school_query: comes as unicode, if can be int, pass as int
    """
    response = nav_helper(request)
    try:
        school_query = int(school_query)
    except ValueError:
        # cant be cast as an int, so we will search for it as a string
        pass
    courses = School.get_courses(school_query)
    if isinstance(courses, tuple):  # FIXME
        response['school'], response['courses'] = courses
        return render(request, 'browse_courses.html', response)
    else:
        raise Http404
def create():
    auth_header = request.headers.get('Authorization')
    if auth_header:
        user_id = uc.decode_auth_token(auth_header)
        if not isinstance(user_id, int):
            return jsonify({"Error": "Failed to authenticate"})
    else:
        return jsonify({"Error": "Failed to authenticate"})

    school_data = request.json

    school_name = school_data['school_name']
    about = school_data['about']
    location = school_data['location']
    admission = school_data['admission']
    image_url = school_data['image_url']

    # try:
    #     image_data = request.files.getlist('files')
    # except Exception:
    #     return jsonify({'Error': 'Failed to get files'})

    # image_location = ''
    # try:
    #     # for image in image_data:
    #     filename = secure_filename(image_url[0].filename)
    #     image_url[0].save(filename)
    #     s3.upload_file(
    #         Bucket=S3_BUCKET_NAME,
    #         Filename=filename,
    #         Key=filename
    #     )
    #     image_location = '{}{}'.format(S3_LOCATION, filename)
    # except Exception as e:
    #     return jsonify({'Error': str(request.files.getlist('image_url'))})

    school = School(school_name=school_name, about=about, location=location, admission=admission, image_url=image_url, user_id=user_id)
    db.session.add(school)

    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        db.session.flush()
        return jsonify({'Error': str(e)})

    return jsonify({'Success': 'New school entry created'})
示例#39
0
def popupdateschools():
    schools = {}
    with app.app_context():
        typeformdata = requests.get(
            'https://api.typeform.com/v1/form/rak9AE?key=***************************************&completed=true&order_by=date_submit&limit=3000'
        ).json()
        responses = typeformdata['responses']
        for user in responses:
            school = user['answers']['dropdown_20497446']
            if school == 'Other':
                if 'textfield_20513659' in user['answers']:
                    school = user['answers']['textfield_20513659']
                else:
                    continue
            if school is not None:
                if school in schools:
                    schools[school] += 1
                else:
                    schools[school] = 1
        try:
            schools['Illinois Institute of Technology'] += 7
            schools['Case Western Reserve University'] += 4
            schools['University of Illinois at Chicago'] += 2
        except KeyError:
            pass
        for school in schools:
            try:
                db_school = School.query.filter_by(name=school).first()
                if db_school is not None:
                    db_school.app_count = schools[school]
                    db_school.dimension = int(
                        min(
                            70, 70 * pow(float(float(schools[school]) / 50),
                                         0.333333333333)))
                    db.session.commit()
                else:
                    dimension = int(
                        min(
                            70, 70 * pow(float(float(schools[school]) / 50),
                                         0.333333333333)))
                    db_school = School(name=school,
                                       app_count=schools[school],
                                       dimension=dimension)
                    db.session.add(db_school)
                    db.session.commit()
            except IntegrityError:
                continue
def print_all(argv):
    '''Print all data in database, ordered with tab heirarchy.

    Keyword arguments:
    argv -- An array of command line arguments passed to the program.
    '''
    for school in School.select():
        print school
        for batch in Batch.select():
            if batch.school.id == school.id:
                print "\t" + str(batch)
                for student in Student.select():
                    if student.batch.id == batch.id:
                        print "\t\t" + str(student)
                        for exercise in Exercise.select():
                            if exercise.student.id == student.id:
                                print "\t\t\t" + str(exercise)
示例#41
0
def school_list():
    if request.args.get("name"):
        schools = School.objects(name__contains = request.args.get("name").upper())
    else:
        schools = School.objects

    json = []

    for school in list(schools):
        city = school.city.name if school.city else ""
        state = school.state.acronym if school.state else ""

        json.append({
            "id": school.code,
            "text": "%s (%s / %s)" % (school.name, city, state)
        })

    return jsonify({ "schools": json })
from models import User
from models import Student


if len(sys.argv) < 2:
    print "Please enter an action"
elif sys.argv[1] in ["create", "print", "insert", "delete"]:
    # print sys.argv[1]
    # if "create":

else:
    print "Undefined action " + sys.argv[1]

if (sys.argv[1] == "create"):
try:
    School.create_table()
except peewee.OpertationalError:
    pass

try:
    Batch.create_table()
except peewee.OpertationalError:
    pass

try:
    User.create_table()
except peewee.OpertationalError:
    pass

try:
    Student.create_table()
 except ValueError, e:
     print "Please set a JSON string"
     return
 try:
     int(argv[2])
     print "Please set a JSON string"
     return
 except ValueError, e:
     batch_id = 0
     student_id = 0
     for k in loaded_json:
         for batch in k["batches"]:
             for student in batch["students"]:
                 for exercise in student["exercises"]:
                     insert_item(["", "insert", "school", k["name"]])
                     for school in School.select():
                         if school.name == k["name"]:
                             school_id = school.id
                     insert_item(["", "insert", "batch", school_id,
                                  batch.get("name")])
                     for orig_batch in Batch.select():
                         if orig_batch.name == batch.get("name"):
                             batch_id = orig_batch.id
                     insert_item(["", "insert", "student", batch_id,
                                  student.get("age"),
                                  student.get("last_name"),
                                  student.get("first_name")])
                     for s in Student.select():
                         if s.first_name == student.get("first_name"):
                             student_id = s.id
                     insert_item(["", "insert", "exercise", student_id,
示例#44
0
    r,out = checkNecessaryParams(request,'province','city','district','telephone','school_name','address')
    if r:
	return InvalidUrl(errorMsg)

    try:
	district = City.objects.filter(province__name = out['province']).filter(name=out['city']).filter(districts__name=out['district'])
    except DoesNotExist,e:
	errorMsg='无法在%s %s找到%s,%s' % (out['province'],out['city'],out['district'],e)
	return InvalidUrl(errorMsg)
    #检查是否是学校管理员电话 
    try:
	sa = SchoolAdministrator.objects.get(telephone = out[telephone])
    except DoesNotExist,e:
	errorMsg='the current user is not a school administrator,only school administrators can create school'
	return InvalidUrl(errorMsg)
    school = School(address = out['address'],name = out['school_name'],status='EI')
    school.save()
    try:
	district.add(school)
	sa.add(school)
    except:
	errorMsg = 'can not add the current school to %s or %s' % (district.name,sa.name)
	return InvalidUrl(errorMsg)
	
    result = '成功注册学校:%s 责任人名字:%s 地区:%s,状态审核中,我们将尽快完成对该学校合法性的审核' % (out['school_name'],sa.name,district.name)
    #后台人员审核通过之后将学校状态置为审核通过
    return RightResponse(result)

def updateSchool(request):
    pass
from __future__ import division
import sys
from models import BaseModel, School, Batch, User, Student, Exercise

actions = ['create', 'print', 'insert', 'delete', 'print_batch_by_school', 'print_student_by_batch', 'print_student_by_school', 'print_family', 'age_average', 'change_batch', 'print_all', 'note_average_by_student', 'note_average_by_batch', 'note_average_by_school', 'top_batch', 'top_school']
if len(sys.argv) < 2:
	print 'Please enter an action'
elif sys.argv[1] not in actions:
	print 'Undefined action' + ' ' + sys.argv[1]
else:
	if sys.argv[1] == 'create':
		
		try:
			School.create_table()
		except peewee.OperationError:
			pass

		try:
			Batch.create_table()
		except peewee.OperationError:
			pass

		try:
			User.create_table()
		except peewee.OperationError:
			pass

		try:
			Student.create_table()
		except peewee.OperationError:
			pass