def getTeacherByLastName(lastName):
    '''
    Get Teacher object from database using their Family Name
    '''
    teacher_object = None
    teacher = Teacher()

    try:
        teacher_object = db.teachers.find_one({'lastName': lastName})
    except:
        print "There was a problem with the database operation"

    if teacher_object:
        if "firstName" in teacher_object:
            teacher.setFirstName(teacher_object["firstName"])

        if "lastName" in teacher_object:
            teacher.setLastName(teacher_object["lastName"])

        if "teacherId" in teacher_object:
            teacher.setTeacherId(teacher_object["teacherId"])
    else:
        print "Could not find teacher with family Name: ", lastName
        return

    return teacher
Exemplo n.º 2
0
    def parse_teacher_params(self):
        filename = self.config['data_storage_path']

        wb = xlrd.open_workbook(filename + '/params.xlsx')
        sheet = wb.sheet_by_index(1)

        teachers = []

        current_row = 1
        while len(sheet.cell(current_row, 0).value) != 0:
            t_id = sheet.cell(current_row, 0).value
            t_name = sheet.cell(current_row, 1).value
            t_discipline = sheet.cell(current_row, 2).value.split(';')  # list
            t_programs = sheet.cell(current_row, 3).value.split(';')  # list
            t_priority = self.__parse_teacher_priority(
                sheet.cell(current_row, 4).value)
            t_ability = self.__parse_teacher_ability(
                sheet.cell(current_row, 5).value)
            t_workplan = self.__parse_teacher_workplan(
                sheet.cell(current_row, 4).value)
            t_changeplan = self.__parse_teacher_changeplan(
                sheet.cell(current_row, 4).value)
            teachers.append(
                Teacher(t_id, t_name, t_discipline, t_programs, t_priority,
                        t_ability, t_workplan, t_changeplan))

        return teachers
Exemplo n.º 3
0
    def post(self):
        json_data = request.get_json()

        data, errors = teacher_schema.load(data=json_data)

        if errors:
            return {
                'message': 'Validation Errors',
                'errors': errors
            }, HTTPStatus.BAD_REQUEST

        if Teacher.get_by_teacher_username(data.get('teacher_username')):
            return {
                'message': 'Teacher already exists'
            }, HTTPStatus.BAD_REQUEST

        teacher = Teacher(**data)

        teacher.save()

        return teacher_schema.dump(teacher).data, HTTPStatus.CREATED
Exemplo n.º 4
0
def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('goals',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('key', sa.String(length=50), nullable=False),
    sa.Column('name', sa.String(length=100), nullable=False),
    sa.Column('icon', sa.String(), nullable=False),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('teachers',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(length=100), nullable=False),
    sa.Column('about', sa.String(length=1000), nullable=False),
    sa.Column('rating', sa.Integer(), nullable=False),
    sa.Column('picture', sa.String(), nullable=False),
    sa.Column('price', sa.Integer(), nullable=False),
    sa.Column('free', sa.String(), nullable=False),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('teachers_goals',
    sa.Column('teacher_id', sa.Integer(), nullable=True),
    sa.Column('goal_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['goal_id'], ['goals.id'], ),
    sa.ForeignKeyConstraint(['teacher_id'], ['teachers.id'], )
    )
    # ### end Alembic commands ###

    goals = []
    for goal in reader.get_all_goals():
        goals.append(
            Goal(
                key=goal['key'],
                name=goal['name'],
                icon=goal['icon']
            ))

    teachers = []
    for teacher in reader.get_all_teachers():
        teachers.append(
            Teacher(
                id=teacher['id'],
                name=teacher['name'],
                about=teacher['about'],
                rating=teacher['rating'],
                picture=teacher['picture'],
                price=teacher['price'],
                goals=[goal for goal in goals if goal.key in teacher['goals']],
                free=json.dumps(teacher['free'])
            ))

    db.session.add_all(goals)
    db.session.add_all(teachers)
    db.session.commit()
Exemplo n.º 5
0
def signup():
    id_number = request.json['id_number']
    full_name = request.json['full_name']
    password = request.json['password']
    accumulated_score = '100'
    user_group = request.json['user_group']
    # teacher = request.json['teacher_checkbox']

    if Student.get_or_none(id_number=id_number):
        resp = {"success": False}
        return jsonify(resp)
        # return jsonify(False)

    if Teacher.get_or_none(id_number=id_number):
        resp = {"success": False}
        return jsonify(resp)

    if user_group == "Student":
        new_user = Student(id_number=id_number,
                           full_name=full_name,
                           password=password,
                           accumulated_score=accumulated_score)

    if user_group == "Teacher":
        new_user = Teacher(id_number=id_number,
                           full_name=full_name,
                           password=password)

    if not new_user.save():
        resp = {"success": False}
        return jsonify(resp)

    access_token = create_access_token(identity=new_user.id_number)
    resp = {"success": True, "auth_token": access_token}

    return jsonify(resp)
Exemplo n.º 6
0
def login():
    user_list = _login()
    if user_list:
        user_list = user_list[1:-1]
        auth = user_list[9]
        user = None
        if auth == "stu":
            print("身份:学生")
            user = Student(*user_list)
        elif auth == "tea":
            print("身份:老师")
            user = Teacher(*user_list)
        elif auth == "admin":
            print("身份:管理员")
            user = Admin(*user_list)
        return user
Exemplo n.º 7
0
def _register(user_type, *args, **kwargs):
    # *args **kwargs 可变长传参
    #  工厂模式
    if user_type == "stu":
        # 学生用户
        user = Student(*args, **kwargs, auth="stu")
    elif user_type == "tea":
        # 老师
        user = Teacher(*args, **kwargs, auth="tea")
    elif user_type == "admin":
        # 管理员
        user = Admin(*args, **kwargs, auth="admin")
    else:
        raise TypeError("类型错误!")
    #  使用多态特性
    user.insert_one()
Exemplo n.º 8
0
def seed_teachers(db):
    for teach in teachers:
        teacher = teach.copy()
        user = UserModel.query.filter_by(
            username=teacher.pop('username')).first()

        if teacher['is_ausbildung'] == True:
            ausbilder = Teacher.query.filter(
                Teacher.user.has(username=teacher['ausbilder'])).first()
            if ausbilder:
                teacher['ausbilder'] = ausbilder

        if user:
            new_teacher = Teacher(**teacher, user_id=user.id)
            db.session.add(new_teacher)
            db.session.commit()
Exemplo n.º 9
0
    def get(self, teacher_username):
        teacher = Teacher.get_by_teacher_username(
            teacher_username=teacher_username)

        if teacher is None:
            return {'message': 'teacher does not exist'}, HTTPStatus.NOT_FOUND

        current_teacher = get_jwt_identity()

        if current_teacher == teacher.teacher_id:
            data = teacher_schema.dump(teacher).data

        else:
            data = teacher_public_schema.dump(teacher).data

        return data, HTTPStatus.OK
Exemplo n.º 10
0
def login():

    id_number = request.json['id_number']
    password = request.json['password']

    student_check = Student.get_or_none(id_number=id_number)
    teacher_check = Teacher.get_or_none(id_number=id_number)

    if student_check is not None:

        if not password == student_check.password:
            response = {"success": False}
            return jsonify(response)

        else:
            access_token = create_access_token(
                identity=student_check.id_number)
            response = {
                "success": True,
                "authToken": access_token,
                "id": student_check.id,
                "id_number": id_number,
                "full_name": student_check.full_name,
                "isStudent": True
            }
            return jsonify(response)
    else:
        if not password == teacher_check.password:
            response = {"success": False}
            return jsonify(response)
        else:
            access_token = create_access_token(
                identity=teacher_check.id_number)
            response = {
                "success": True,
                "authToken": access_token,
                "id": teacher_check.id,
                "id_number": id_number,
                "full_name": teacher_check.full_name,
                "isStudent": False
            }
            return jsonify(response)
Exemplo n.º 11
0
def RegisterUser():
    if request.method == "GET":
        flash("Please login first!! (GET method used for registration)",
              "info")
        return redirect(url_for("home"))

    user_type = request.form.get("user_type")  # Student or Teacher
    name = request.form.get("name")  # Name
    email = request.form.get("email")  # Email
    password = request.form.get("password")  # Password
    verify_password = request.form.get("verify_password")

    if password != verify_password:
        flash("Password and verified password do not match!", "warning")
        return redirect(url_for("home"))

    if Teacher.query.filter_by(email=email).first() or Student.query.filter_by(
            email=email).first():
        flash(f"User with email {email} already exists!", "danger")
        return redirect(url_for("home"))

    newUser = None
    if user_type == "student":
        newUser = Student(name, email, password)
    elif user_type == "teacher":
        newUser = Teacher(name, email, password)
    else:
        flash(f"Invalid user type {user_type}!", "danger")
        return redirect(url_for("home"))
    db.session.add(newUser)
    db.session.commit()

    session["name"] = newUser.name
    session["email"] = newUser.email
    session["verified"] = newUser.verified
    session["user_type"] = newUser.user_type

    flash("Registered successfully!", "success")
    return redirect(url_for("dashboard"))
Exemplo n.º 12
0
    def post(self):
        json_data = request.get_json()
        teacher_username = json_data.get('teacher_username')
        teacher_password = json_data.get('teacher_password')

        teacher = Teacher.get_by_teacher_username(
            teacher_username=teacher_username)

        if not teacher or not check_password(teacher_password,
                                             teacher.teacher_password):
            return {
                'message': 'username or password is incorrect'
            }, HTTPStatus.UNAUTHORIZED

        teacher_access_token = create_access_token(identity=teacher.teacher_id,
                                                   fresh=True)
        teacher_refresh_token = create_refresh_token(
            identity=teacher.teacher_id)
        return {
            'teacher_access_token': teacher_access_token,
            'teacher_refresh_token': teacher_refresh_token
        }, HTTPStatus.OK
Exemplo n.º 13
0
def show():
    current_user = request.json['id_number']
    my_account = Student.get_or_none(id_number=current_user)
    if my_account is None:
        my_account = Teacher.get_or_none(id_number=current_user)
        resp = {
            "isStudent": False,
            "id_number": my_account.id_number,
            "full_name": my_account.full_name
        }

        return jsonify(resp)

    resp = {
        "isStudent": True,
        "id_number": my_account.id_number,
        "full_name": my_account.full_name,
        "creativity_score": my_account.creativity_score,
        "leadership_score": my_account.leadership_score,
        "respect_score": my_account.respect_score,
        "accumulated_score": my_account.accumulated_score
    }

    return jsonify(resp)
Exemplo n.º 14
0
import peeweedbevolve
from models import *    # all import (*) being handled by __init__.py inside the 'models' folder  
from models.base_model import db

# =================================================================


from models.student import Student
from models.teacher import Teacher
from models.calendar import *
import random
import names

# seeding
Teacher(id_number=0, full_name="admin", password="******").save()
Student(id_number=11, full_name="fav student", password="******", 
creativity_score=random.randint(1000,5000), leadership_score=random.randint(1000,5000),
respect_score=random.randint(1000,5000)).save()


for i in random.sample(range(1,5),3):
    # Teacher
    tch_name = names.get_full_name()
    first, last = tch_name.split()
    Teacher(id_number=i, full_name=tch_name, password=last).save()

    # Student
    std_name = names.get_full_name()
    first, last = std_name.split()
    Student(id_number=i, full_name=std_name, password=last, 
Exemplo n.º 15
0
from models.base_model import db

# =================================================================

from models.student import Student
from models.teacher import Teacher
from models.calendar import *
from models.favourite import *
import random
import names

# restart database
Student_Activity.delete().execute()
Student_Club.delete().execute()
Student.delete().execute()
Teacher.delete().execute()
Club.delete().execute()
Activity.delete().execute()

# seeding
Teacher(id_number=0, full_name="Professor Albus Dumbledore",
        password="******").save()
Student(id_number=11,
        full_name="Hermione Granger",
        password="******",
        creativity_score=67,
        leadership_score=88,
        respect_score=76).save()

# Activity
Activity(
Exemplo n.º 16
0
from datasets.stdataset import ST_DATASET
from models.teacher import Teacher
from models.student import Student

dataset = ST_DATASET

stlist = []
teacherlist = []

for data in dataset:
    # print(data, end='\n\n')
    # print(data['type'])
    # print(data.get('ptype', 123), end='\n\n')
    ptype = data['type']

    if ptype == 'student':
        # year, classname, name, dept, ptype, identity, bloodg
        student = Student(data['year'], data['classname'], data['name'],
                          data['dept'], data['type'], data['id'],
                          data['bloodg'])
        stlist.append(student)
    elif ptype == 'teacher':
        #name, identity, ptype, dept, designation, salary, bloodg
        teacher = Teacher(data['name'], data['id'], data['type'], data['dept'],
                          data['designation'], data['salary'], data['bloodg'])
        teacherlist.append(teacher)

print(stlist, end='\n\n')
print(teacherlist)
Exemplo n.º 17
0
    def get(self):
        print ""
                
        combinations = db.GqlQuery("SELECT * FROM Combination WHERE class_id >= :1 AND class_id < :2", "3", u"3" + u"\ufffd").fetch(9999)
        combinations.extend(db.GqlQuery("SELECT * FROM Combination WHERE class_id >= :1 AND class_id < :2", "4", u"4" + u"\ufffd").fetch(9999))
        
        # All teachers that are assigned to a subject
        workingTeachers = [];
        
        for comb in combinations:
            workingTeachers.append(comb.teacher.key().name())
        
        workingTeachers = Set(workingTeachers)
        workingTeachers = list(workingTeachers)

        
        # Teachers not assigned to a subject        
        temp = Teacher.all().fetch(9999)
        otherTeachers = [teacher.key().name() for teacher in temp]
        
        for teacher in workingTeachers:
            otherTeachers.remove(teacher)
        
        groupA = otherTeachers[:40]
        groupB = otherTeachers[37:]

        
        # Get all combinations for years 3 and 4
        
        combinations = db.GqlQuery("SELECT * FROM Combination WHERE class_id >= :1 AND class_id < :2", "3", u"3" + u"\ufffd").fetch(9999)
        combinations.extend(db.GqlQuery("SELECT * FROM Combination WHERE class_id >= :1 AND class_id < :2", "4", u"4" + u"\ufffd").fetch(9999))
        
        print "Conversion for years 3 and 4:"
        
        for comb in combinations:
            oldTeacher = comb.teacher.key().name()
            oldTeacherIndex = workingTeachers.index(oldTeacher)
            newTeacherKey = groupA[oldTeacherIndex]
            newTeacher = Teacher.all().filter("__key__", Key.from_path('Teacher',newTeacherKey)).get()
            print "old: "+oldTeacher+" - new: "+newTeacher.key().name()
            comb.teacher = newTeacher
            comb.save()
        
        
        # Get all combinations for years 5 and 6
        
        combinations = db.GqlQuery("SELECT * FROM Combination WHERE class_id >= :1 AND class_id < :2", "5", u"5" + u"\ufffd").fetch(9999)
        combinations.extend(db.GqlQuery("SELECT * FROM Combination WHERE class_id >= :1 AND class_id < :2", "6", u"6" + u"\ufffd").fetch(9999))
        
        # All teachers that are assigned to a subject
        workingTeachers = [];
        
        for comb in combinations:
            workingTeachers.append(comb.teacher.key().name())
        
        workingTeachers = Set(workingTeachers)
        workingTeachers = list(workingTeachers)        
        
        combinations = db.GqlQuery("SELECT * FROM Combination WHERE class_id >= :1 AND class_id < :2", "5", u"5" + u"\ufffd").fetch(9999)
        combinations.extend(db.GqlQuery("SELECT * FROM Combination WHERE class_id >= :1 AND class_id < :2", "6", u"6" + u"\ufffd").fetch(9999))
        
        
        print "Conversion for years 5 and 6:"
        
        for comb in combinations:
            oldTeacher = comb.teacher.key().name()
            oldTeacherIndex = workingTeachers.index(oldTeacher)
            newTeacherKey = groupB[oldTeacherIndex]
            newTeacher = Teacher.all().filter("__key__", Key.from_path('Teacher',newTeacherKey)).get()
            print "old: "+oldTeacher+" - new: "+newTeacher.key().name()
            comb.teacher = newTeacher
            comb.save()
Exemplo n.º 18
0
    def get(self):
        
        # Load all Guardians
        path = os.path.join(os.path.dirname(__file__), 'data/voogdouder.txt')
        my_file = open(path)
        fileReader = csv.reader(my_file, delimiter=";") 
        for row in fileReader: 
            new_guardian = Guardian(key_name=row[0].strip())
            new_guardian.title=row[1].strip()
            new_guardian.initials=row[2].strip()
            new_guardian.preposition=row[3].strip()
            new_guardian.lastname=row[4].strip()
            new_guardian.streetname=row[6].strip()
            new_guardian.housenumber=row[7].strip()
            new_guardian.city=row[8].strip()
            new_guardian.postalcode=row[9].strip()
            new_guardian.email=row[12].strip()
            new_guardian.save()
            print "Guardian " + new_guardian.key().id_or_name() + " stored"

        # Load all Students
        path = os.path.join(os.path.dirname(__file__), 'data/leerlingen.txt')
        my_file = open(path)
        fileReader = csv.reader(my_file, delimiter=";") 
        for row in fileReader: 
            new_student = Student(key_name=row[0].strip())
            new_student.firstname=row[1].strip()
            new_student.preposition=row[2].strip()
            new_student.lastname=row[3].strip()
            new_student.gender=row[4].strip()
            new_student.class_id=row[5].strip()
            new_student.guardian=Guardian.all().filter("__key__ >=", Key.from_path('Guardian', row[6].strip())).get()
            new_student.save()
            print "Student " + new_student.key().id_or_name() + " stored"
            
        # Load all Teachers
        path = os.path.join(os.path.dirname(__file__), 'data/docenten.txt')
        my_file = open(path)
        fileReader = csv.reader(my_file, delimiter=";") 
        for row in fileReader:
            new_teacher = Teacher(key_name=row[0].strip())
            new_teacher.name=row[1].strip()
            new_teacher.boxnumber=int(row[2].strip())
            new_teacher.email=row[3].strip()
            new_teacher.save()
            print "Teacher " + new_teacher.key().id_or_name() + " stored"
            
        # Load all Subjects
        path = os.path.join(os.path.dirname(__file__), 'data/vakken.txt')
        my_file = open(path)
        fileReader = csv.reader(my_file, delimiter=";") 
        for row in fileReader:
            new_subject = Subject(key_name=row[0].strip())
            new_subject.name=row[1].strip()
            new_subject.save()
            print "Subject " + new_subject.key().id_or_name() + " stored"

        # Load all Students
        path = os.path.join(os.path.dirname(__file__), 'data/docent_vak.txt')
        my_file = open(path)
        fileReader = csv.reader(my_file, delimiter=";") 
        for row in fileReader: 
            new_combination = Combination()
            new_combination.class_id=row[0].strip()
            new_combination.subject=Subject.all().filter("__key__ >=", Key.from_path('Subject', row[1].strip())).get()
            new_combination.teacher=Teacher.all().filter("__key__ >=", Key.from_path('Teacher', row[2].strip())).get()
            new_combination.save()
            print "Combination " + str(new_combination.key().id_or_name()) + " stored"
        self.redirect("/fix")
# sys.path.append('/models')
import time
import datetime
from pymongo import MongoClient
from bson.dbref import DBRef
from bson import ObjectId
from models.teacher import Teacher

## Initialize Database
mongo_uri = "mongodb://*****:*****@ds133632.mlab.com:33632/himama-dev"
client = MongoClient(mongo_uri)

db = client['himama-dev']

## Initialize Teacher Object
jane = Teacher()


def getTeacherById(teacherId):
    '''
    Get Teacher object from database using their Teacher ID
    '''
    teacher_object = None
    teacher = Teacher()

    try:
        teacher_object = db.teachers.find_one({'teacherId': teacherId})
    except:
        print "There was a problem with the database operation"

    if teacher_object:
Exemplo n.º 20
0
    def post(self, arg):
        event = Event.get_by_id(int(arg))
        notifications = []
        appointments = []
        
        template_values = {
            'event': event,
            'appointments': appointments,
            'notifications': notifications, 
            'logoutlink': users.create_logout_url("/") 
        }
        
        if not event: 
            notifications.append("Er is geen ouderavondreeks gevonden met het nummer " + str(arg))
            path = os.path.join(os.path.dirname(__file__), '../templates/administration/event-appointments.html')
            self.response.out.write(template.render(path, template_values))
            return
        
        code = self.request.POST['search-code']
        method = self.request.POST['search-on']
        
        if not code:
            notifications.append("Er dient een docentcode of voogdnummer ingevoerd te worden.")
        if not method:
            notifications.append("Er dient aangegeven te worden of er op docent of voogd gezocht wordt.")
        if not (code and method):
            path = os.path.join(os.path.dirname(__file__), '../templates/administration/event-appointments.html')
            self.response.out.write(template.render(path, template_values))
            return
        
        if method == 'guardian':
            guardian = Guardian.get_by_key_name(code)
            if not guardian:
                notifications.append("Er is geen voogd gevonden met het voogdnummer " + str(code))
                path = os.path.join(os.path.dirname(__file__), '../templates/administration/event-appointments.html')
                self.response.out.write(template.render(path, template_values))
                return
            
            requests = guardian.all_requests.filter('event', event).fetch(999)
            for request in requests: 
                if request.appointment.get():
                    appointments.append(request.appointment.get()) 
            
            if not appointments:
                notifications.append("Er zijn geen afspraken gevonden voor de voogd met het voogdnummer " + str(code))
                path = os.path.join(os.path.dirname(__file__), '../templates/administration/event-appointments.html')
                self.response.out.write(template.render(path, template_values))
                return
            
#            days = []
#            for appointment in appointments:
#                found = False
#                for day in days:
#                    if day.key().id() == appointment.day.key().id():
#                        found = True
#                        break
#                if not found:
#                    days.append(appointment.day)
#            
#            days_appointments = []
#            for day in days:
#                appointments_in_day = []
#                for appointment in appointments:
#                    if appointment.day.key().id() == day.key().id():
#                        appointments_in_day.append(appointment)
#                
#                days_appointments.append([day, appointments_in_day])
#            
#            days_tables_appointments = []
#            for day_appointments in days_appointments:
#                tables = []
#                for appointment in day_appointments[1]:
#                    if appointment.table not in tables:
#                        tables.append(int(appointment.table))
#                
#                day_tables = []
#                for table in tables:
#                    table_appointments = []
#                    for appointment in day_appointments[1]:
#                        if int(appointment.table) == table:
#                            table_appointments.append(appointment)
#                    day_tables.append([table, table_appointments])
#                days_tables_appointments.append([day_appointments[0], day_tables])
#                
#            day_tables_slots = []
#            for day_tables_appointments in days_tables_appointments:
#                for table_appointments in day_tables_appointments[1]:
#                    table_slots = []
#                    for slot in range(1, day_tables_appointments[0].talks+1):
#                        added = False
#                        for appointment in table_appointments[1]:
#                            if(int(appointment.slot) == slot):
#                                added = True
#                                table_slots.append(appointment)
#                        if not added:
#                            table_slots.append(1)
#                    day_tables_slots.append([day_tables_appointments[0], [table_appointments[0], table_slots]])
        elif method == 'teacher':
            teacher = Teacher.get_by_key_name(code.upper())
            if not teacher:
                notifications.append('Er is geen docent gevonden met de opgegeven docentcode.')
            if teacher:
                subjects = teacher.subjects.fetch(999)
                requests = []
                for subject in subjects:
                    reqs = subject.requests.fetch(999)
                    for req in reqs:
                        requests.append(req)
                appointments = [request.appointment.get() for request in requests if request.appointment.get()]
                if not appointments:
                    notifications.append("Er zijn geen afspraken gevonden voor de docent met docentcode " + str(code))
                    
        path = os.path.join(os.path.dirname(__file__), '../templates/administration/event-appointments.html')
        self.response.out.write(template.render(path, template_values))