예제 #1
0
def create_student():
    try:
        name = input('请输入学生姓名: ').strip()
        age = input('请输入学生年龄: ').strip()
        qq = input('请输入学生qq号码: ').strip()
        student_name_list = [obj['name'] for obj in Student.get_all_obj_list()]
        if name in student_name_list:
            raise Exception('\033[43;1m学生[%s] 已经存在,不可重复创建\033[0m' % (name))
        classes_list = Classes.get_all_obj_list()
        for k, obj in enumerate(classes_list):
            print('%s [%s][%s]校区 班级[%s]'.center(60, '-') \
                  % (k, obj['school_nid'].get_obj_by_uuid(settings.SCHOOL_DB_DIR )['name'],\
                     obj['school_nid'].get_obj_by_uuid(settings.SCHOOL_DB_DIR )['addr'], \
                     obj['name']))
        id = int(input('请选择班级: '))
        class_obj = classes_list[id]
        obj = Student(name, age, qq, class_obj['nid'])
        obj.save()
        status = True
        error = ''
        data='\033[33;1m学生 名字[%s] 年龄[%s] qq[%s] 班级[%s] 创建成功\033[0m' \
             %(obj.name,obj.age,obj.qq,obj.classes_nid.get_obj_by_uuid(settings.CLASSES_DB_DIR )['name'])
        print(data)
    except Exception as e:
        status = False
        error = str(e)
        print('error: %s' % error)
        data = ''
    return {'status': status, 'error': error, 'data': data}
예제 #2
0
	def handle(self, *args, **options):		

		# process arguments
		module_code = args[0]
		wb_file = os.path.join(XLS_ROOT, args[1])

		# open workbook
		wb = xlrd.open_workbook(wb_file)

		# get first sheet
		ws = wb.sheet_by_index(0)
		
		# iterate over rows (ignore first)
		curr_row = 0	
		while curr_row < ws.nrows - 1:
			curr_row += 1
			if ws.cell_type(curr_row, 0) == 1:
				sid = ws.cell_value(curr_row, 0)
				u = User( username=sid )
				if ws.cell_type(curr_row, 1) == 1:
					u.last_name = ws.cell_value(curr_row, 1)
				if ws.cell_type(curr_row, 2) == 1:
					u.first_name = ws.cell_value(curr_row, 2)
				if ws.cell_type(curr_row, 3) == 1:
					u.email = ws.cell_value(curr_row, 3)
				u.save()
				s = Student( user=u )
				s.nickname = ws.cell_value(curr_row, 3)
				s.save()
예제 #3
0
def insert_new_student(name: str, address: str, birth_date: date,
                       courseDuration: int, email: str, password: str):
    flightTimeZero = timedelta(days=0,
                               seconds=0,
                               microseconds=0,
                               milliseconds=0,
                               minutes=0,
                               hours=0,
                               weeks=0)

    if ((Student.get(email=email)) != None):
        abort(400, 'Email já cadastrado')

    stud = Student(name=name,
                   address=address,
                   email=email,
                   password=password,
                   birth_date=birth_date,
                   flightTime=flightTimeZero,
                   licenseAvailable=False,
                   courseDuration=courseDuration)

    commit()

    return {"endpoint": "api/students/" + str(stud.ID)}
예제 #4
0
    def handle(self, *args, **options):

        # process arguments
        module_code = args[0]
        wb_file = os.path.join(XLS_ROOT, args[1])

        # open workbook
        wb = xlrd.open_workbook(wb_file)

        # get first sheet
        ws = wb.sheet_by_index(0)

        # iterate over rows (ignore first)
        curr_row = 0
        while curr_row < ws.nrows - 1:
            curr_row += 1
            if ws.cell_type(curr_row, 0) == 1:
                sid = ws.cell_value(curr_row, 0)
                u = User(username=sid)
                if ws.cell_type(curr_row, 1) == 1:
                    u.last_name = ws.cell_value(curr_row, 1)
                if ws.cell_type(curr_row, 2) == 1:
                    u.first_name = ws.cell_value(curr_row, 2)
                if ws.cell_type(curr_row, 3) == 1:
                    u.email = ws.cell_value(curr_row, 3)
                u.save()
                s = Student(user=u)
                s.nickname = ws.cell_value(curr_row, 3)
                s.save()
예제 #5
0
    def signup(self, request, user):
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.save()

        student = Student()
        student.user = user
        student.save()
예제 #6
0
def create_student():
    try:
        print('创建学生'.center(60, '='))
        name = input("请输入姓名: ").strip()
        age = input("请输入年龄: ").strip()
        if name == '' or age == '':
            raise Exception("输入不能为空")
        if age.isdigit():
            age = int(age)
        else:
            raise Exception("年龄应该是数字")
        student_name_list = [obj.name for obj in Student.get_all_obj_list()]
        if name in student_name_list:
            raise Exception("学生[%s]已存在" % name)

        school_list = School.get_all_obj_list()
        for k, obj in enumerate(school_list):
            print(k, '[%s] [%s]校区' % (obj.name, obj.addr))
        s_sid = input("请选择学校:")
        if s_sid.isdigit():
            s_sid = int(s_sid)
            if s_sid >= len(school_list):
                raise Exception("输入的学校不存在")
        else:
            raise Exception("输入的学校不存在")

        classes_list = Classes.get_all_obj_list()
        for k, obj in enumerate(classes_list):
            print(k, obj.name,
                  '[%s]校区' % (obj.school_nid.get_obj_by_nid().addr))
        sid = input("请选择班级:")
        if sid.isdigit():
            sid = int(sid)
            if sid >= len(classes_list):
                raise Exception("输入的班级不存在")
        else:
            raise Exception("输入的班级不存在")
        if school_list[s_sid].nid.nid != classes_list[sid].school_nid.nid:
            raise Exception("[%s][%s]校区没有 [%s]班级" %
                            (school_list[s_sid].name, school_list[s_sid].addr,
                             classes_list[sid].name))

        print(
            "学费为: ", classes_list[sid].course_to_teacher_list_nid.
            get_obj_by_nid().course_nid.get_obj_by_nid().price)
        obj = Student(name, age, classes_list[sid].nid)
        obj.save()
        status = True
        error = ''
        data = '\033[33;1m学生[%s] 创建成功\033[0m' % name
    except Exception as e:
        status = False
        error = str(e)
        data = ''

    return {'status': status, 'error': error, 'data': data}
예제 #7
0
    def setUp(self):

        self.client = Client()

        self.user = MyUser(
            username='******',
            email='*****@*****.**',
            is_active=True,
            is_staff=True,
            is_superuser=True,
        )
        self.user.set_password('test')
        self.user.save()

        self.client.login(username='******', password='******')

        teacher = MyUser.objects.create(username='******')
        students_lst = []
        groups_lst = []

        for counter in range(10):
            students_lst.append(Student(id=counter))
            groups_lst.append(Group(id=counter, teacher=teacher))
        Student.objects.bulk_create(students_lst)

        for group in groups_lst:
            group.students.set(students_lst)
        Group.objects.bulk_create(groups_lst)
예제 #8
0
def show_student(user):
    try:
        choice_list = []
        classes_list = Classes.get_all_obj_list()
        student_list = Student.get_all_obj_list()
        for k, obj in enumerate(classes_list):
            if user == obj.course_to_teacher_list_nid.get_obj_by_nid(
            ).teacher_nid.get_obj_by_nid().name:
                print(k, '\033[33;1m [%s][%s]校区  班级[%s] [%s]期 \033[0m' \
                      % (obj.school_nid.get_obj_by_nid().name, obj.school_nid.get_obj_by_nid().addr,
                         obj.nid.get_obj_by_nid().name,
                         obj.course_to_teacher_list_nid.get_obj_by_nid().course_nid.get_obj_by_nid().period))
                choice_list.append(classes_list[k])
        choice = input("请选择查看的班级: ").strip()
        if choice.isdigit():
            choice = int(choice)
            if choice >= len(choice_list):
                raise Exception("班级选择错误")
        else:
            raise Exception("班级选择错误")
        for k, obj in enumerate(student_list):
            if choice_list[choice].nid.nid == student_list[k].classes_nid.nid:
                print('\033[33;1m班级[%s] [%s]期 学员[%s] 成绩[%s]\033[0m' %
                      (obj.classes_nid.get_obj_by_nid().name,
                       obj.classes_nid.get_obj_by_nid(
                       ).course_to_teacher_list_nid.get_obj_by_nid().
                       course_nid.get_obj_by_nid().period, obj.name,
                       obj.score.get(obj.classes_nid.get_obj_by_nid().
                                     course_to_teacher_list_nid.nid)))
    except Exception as e:
        status = False
        error = str(e)
        data = ''
        return {'status': status, 'error': error, 'data': data}
예제 #9
0
def show_students(user):
    for obj in Student.get_all_obj_list():
        print('\033[33;1m班级[%s] [%s]期 学员[%s] 成绩[%s]\033[0m' %
              (obj.classes_nid.get_obj_by_nid().name,
               obj.classes_nid.get_obj_by_nid().course_to_teacher_list_nid.
               get_obj_by_nid().course_nid.get_obj_by_nid().period, obj.name,
               obj.score.get(obj.classes_nid.get_obj_by_nid().
                             course_to_teacher_list_nid.nid)))
예제 #10
0
def change_score(user):
    try:
        choice_list = []
        classes_list = Classes.get_all_obj_list()
        student_list = Student.get_all_obj_list()
        for k, obj in enumerate(classes_list):
            if user == obj.course_to_teacher_list_nid.get_obj_by_nid(
            ).teacher_nid.get_obj_by_nid().name:
                print(k, '\033[33;1m [%s][%s]校区  班级[%s] [%s]期 \033[0m' \
                      % (obj.school_nid.get_obj_by_nid().name, obj.school_nid.get_obj_by_nid().addr,
                         obj.nid.get_obj_by_nid().name,
                         obj.course_to_teacher_list_nid.get_obj_by_nid().course_nid.get_obj_by_nid().period))
                choice_list.append(classes_list[k])
        choice = input("请选择查看的班级: ").strip()
        if choice.isdigit():
            choice = int(choice)
            if choice >= len(choice_list):
                raise Exception("班级选择错误")
        else:
            raise Exception("班级选择错误")
        tmp = []
        for k, obj in enumerate(student_list):
            if choice_list[choice].nid.nid == student_list[k].classes_nid.nid:
                tmp.append(k)
                print(
                    k, '\033[33;1m班级[%s] [%s]期 学员[%s] 成绩[%s]\033[0m' %
                    (obj.classes_nid.get_obj_by_nid().name,
                     obj.classes_nid.get_obj_by_nid(
                     ).course_to_teacher_list_nid.get_obj_by_nid().course_nid.
                     get_obj_by_nid().period, obj.name,
                     obj.score.get(obj.classes_nid.get_obj_by_nid().
                                   course_to_teacher_list_nid.nid)))
        change = input("选择要修改的学生:")
        if change.isdigit():
            change = int(change)
            if change in tmp:
                num = input("请输入该学生的成绩:")
                file_path = os.path.join(settings.STUDENT_DB,
                                         student_list[change].nid.nid)
                student_list[change].score.set(
                    student_list[change].classes_nid.get_obj_by_nid().
                    course_to_teacher_list_nid.nid, num)
                obj = student_list[change]
                # pickle.dump(obj, open(file_path, 'wb'))
                with open(file_path, 'wb') as fp:
                    pickle.dump(obj, fp)
                print(
                    obj.score.get(obj.classes_nid.get_obj_by_nid().
                                  course_to_teacher_list_nid.nid))
                status = True
                error = ''
                data = '\033[33;1m学生[%s] 成绩为[%s]\033[0m' % (
                    student_list[change].name, num)
    except Exception as e:
        status = False
        error = str(e)
        data = ''
    return {'status': status, 'error': error, 'data': data}
예제 #11
0
def create_objects():
    result = dict()
    for i in range(1, 7):
        tmp = dict()
        for x in range(0, 3):
            obj = Student("Viorel", "FI-131", 9.5)
            tmp[x] = obj.__dict__
        result[i] = tmp
    return result
예제 #12
0
def student_info():
    """
    查看学生信息
    """
    for obj in Student.get_all_obj_list():
        # print(type(obj['classes_nid']))
        # print(obj['classes_nid'].get_obj_by_uuid()['school_nid'].get_obj_by_uuid()['name'])
        print('\033[33;1m学生 名字[%s] 年龄[%s] qq[%s] [%s] [%s]校区 班级[%s] \033[0m'\
              % (obj['name'],obj['age'],obj['qq'],\
                 obj['classes_nid'].get_obj_by_uuid(settings.CLASSES_DB_DIR)['school_nid'].get_obj_by_uuid(settings.SCHOOL_DB_DIR)['name'],\
                 obj['classes_nid'].get_obj_by_uuid(settings.CLASSES_DB_DIR)['school_nid'].get_obj_by_uuid(settings.SCHOOL_DB_DIR)['addr'],\
                 obj['classes_nid'].get_obj_by_uuid(settings.CLASSES_DB_DIR)['name']))
    def handle(self, *args, **kwargs):
        count = kwargs['count']
        for i in range(count):
            u = User(username=f'new_user00{i}', password='******')
            u.save()
            p = Profile.objects.get(user=u)
            p.user = u
            p.first_name = 'SchoolStudent'
            p.last_name = str(i)
            p.birthdate = generate_birthdate()
            p.date_joined = generate_birthdate()
            p.status = 'S'
            p.save()

            s = Student(
                profile=p,
                class_joined=random.randint(1, 5),
                current_class=random.randint(6, 10),
                class_passed=False,
            )
            s.save()
            s.current_teachers.add(get_teacher())
            s.save()

        self.stdout.write(self.style.SUCCESS('Students Created Successfully'))
예제 #14
0
def loginURL(email: str, password: str):
    student = Student.get(email=email)
    instructor = Instructor.get(email=email)
    admin = Admin.get(email=email)

    login_params = {}
    if(not(student == None) and not(instructor == None) and not(admin == None)):
        abort(404, 'Email não cadastrado')

    if not(student == None):
        if(not(student.password == password)):
            abort(400, 'Senha incorreta')
        else:
            login_params = {
                "ID": student.ID,
                "email": student.email,
                "password": student.password,
                "type": 'student',
                "name": student.name,
                "url": "/dashboard-student/"
            }
            return login_params

    if(not (instructor == None)):
        if(not(instructor.password == password)):
            abort(400, 'Senha incorreta')
        else:
            login_params = {
                "ID": instructor.ID,
                "email": instructor.email,
                "password": instructor.password,
                "type": 'instructor',
                "name": instructor.name,
                "url": "/dashboard-instructor/"
            }
            return login_params

    if(not (admin == None)):
        if(not(admin.password == password)):
            abort(400, 'Senha incorreta')
        else:
            login_params = {
                "ID": admin.ID,
                "email": admin.email,
                "password": admin.password,
                "type": 'admin',
                "name": 'Administrador',
                "url": "/dashboard-administrator/"
            }
            return login_params
예제 #15
0
    def post(self):

        form = RegisterForm()

        if form.validate_on_submit():

            photo = upload_file(request.files['photo'])

            obj = Student(name=form.name.data,
                          cpf=form.cpf.data,
                          phone=form.phone.data,
                          email=form.email.data,
                          photo=photo)

            db.session.add(obj)
            db.session.commit()

            return {'success': True, 'id': obj.id}

        else:

            return {'success': False, "errors": form.errors}
예제 #16
0
def register():
    db_path = os.path.join(settings.ACCOUNTS_DB_DIR, 'students')
    #print(db_path)
    exit_flag = False
    while not exit_flag:
        print("学生用户注册".center(50, "="))
        #username == student.name
        username = input("请输入您要注册的用户名【用户名必须为真实姓名】:").strip()
        if username in os.listdir(db_path):
            print("该用户名已注册,不能重新注册!")
            return False
        else:

            student_list = Student.get_all_obj_list()
            #print(student_list)
            for obj in student_list:
                #print(obj)
                if username == obj['name']:
                    # student_obj = obj
                    password = input("请输入密码:").strip()
                    re_password = input('再次确认密码:').strip()
                    if password != re_password:
                        print('\033[31;1m两次输入的密码不一致!\033[0m')
                        continue
                    userdata = {
                        "username": username,
                        "password": password,
                        'locked': False,
                        'authority': False,
                        "student_nid": obj['nid']
                    }
                    dump_user(userdata, db_path)
                    print('\033[31;1m学生[%s] 注册成功!\033[0m' % username)
                    return True
            else:
                print("学生[%s] 不存在,无法注册!请联系管理员创建 学生[%s]!" %
                      (username, username))
                # exit_flag = True
                return False
예제 #17
0
def login():
    msg = '''
    1.注册
    2.登入
    '''
    while True:
        print(msg)
        choice = input("请选择操作: ").strip()
        if choice == '1':
            ret = admin_service.create_student()
        elif choice == '2':
            ret = Student.login()
        else:
            print("输入有误")
            continue

        if ret:
            if ret['status']:
                print(ret['data'].center(60, '-'))
                if choice == '2':
                    main(ret['user'])
            else:
                print(ret['error'].center(60, '-'))
예제 #18
0
def set_student_score():
    """
    设置学生分数
    """
    student_list = Student.get_all_obj_list()
    for k,obj in enumerate(student_list):
        # print(type(obj['classes_nid']))
        # print(obj['classes_nid'].get_obj_by_uuid()['school_nid'].get_obj_by_uuid()['name'])
        print('\033[33;1m %s 学生 名字[%s] 年龄[%s] qq[%s] [%s] [%s]校区 班级[%s] \033[0m'\
              % (k,obj['name'],obj['age'],obj['qq'],\
                 obj['classes_nid'].get_obj_by_uuid(settings.CLASSES_DB_DIR)['school_nid'].get_obj_by_uuid(settings.SCHOOL_DB_DIR)['name'],\
                 obj['classes_nid'].get_obj_by_uuid(settings.CLASSES_DB_DIR)['school_nid'].get_obj_by_uuid(settings.SCHOOL_DB_DIR)['addr'],\
                 obj['classes_nid'].get_obj_by_uuid(settings.CLASSES_DB_DIR)['name']))
    id=int(input('请选择学生: '))
    student_obj = student_list[id]
    #print(student_obj)
    score = input('班级[%s] 学生[%s] 设置分数:'%(student_obj['classes_nid'].get_obj_by_uuid(settings.CLASSES_DB_DIR)['name'],student_obj['name']))
    course_to_teacher_nid = student_obj['classes_nid'].get_obj_by_uuid(settings.CLASSES_DB_DIR)['course_to_teacher_list']['nid']
    student_obj['score'].set(course_to_teacher_nid,score)
    # print(student_obj['score'])
    # print(student_obj['score'].nid)
    # print(student_obj['score'].score_dict)
    # print(student_obj['score'].data)
    student_obj['score'].save()
def populate_database():
    if not (Student.select().exists()):
        flightTimeZero = timedelta(days=0,
                                   seconds=0,
                                   microseconds=0,
                                   milliseconds=0,
                                   minutes=0,
                                   hours=0,
                                   weeks=0)
        stud1 = Student(name='Fábio',
                        address='Av. Angélica, 728',
                        birth_date='1998-10-28',
                        flightTime=flightTimeZero)
        stud2 = Student(name='Gabriel',
                        address='Rua Timbiras, 879',
                        birth_date='1997-06-15',
                        flightTime=flightTimeZero)
        stud3 = Student(name='Douglas',
                        address='Alameda Santos, 134',
                        birth_date='1996-12-01',
                        flightTime=flightTimeZero)
        stud4 = Student(name='Enrique',
                        address='Rua Cactos, 867',
                        birth_date='1997-1-25',
                        flightTime=flightTimeZero)
        stud5 = Student(name='Gabriel',
                        address='Rua Incas, 1378',
                        birth_date='1996-2-28',
                        flightTime=flightTimeZero)

    if not (Instructor.select().exists()):
        instr1 = Instructor(name='Jerônimo',
                            license_number=9853294,
                            address='Rua dos camelos, 1386',
                            birth_date='1985-4-23',
                            course_name='Pilotagem de helicópteros',
                            graduation_date='2014-01-20',
                            institution='Escola XX de Julho')

        instr2 = Instructor(
            name='Luciana',
            license_number=7548125,
            address='Av. Kennedy, 12',
            birth_date='1974-2-21',
            course_name='Mecânica e pilotagem de aeronaves de pequeno porte',
            graduation_date='2002-1-31',
            institution='Escola de vôo de Cotia')

        instr3 = Instructor(
            name='Alberto',
            license_number=1324578,
            address='Estrada do jaguar, km 72',
            birth_date='1990-7-18',
            course_name='Especialização em aviões de grande porte',
            graduation_date='2016-12-14',
            institution='Centro de aviação CVT')

        instr4 = Instructor(name='Juvenal',
                            license_number=8987456,
                            address='Av. Osnir Santos, 445',
                            birth_date='1973-5-11',
                            course_name='Instruções de vôo gerais',
                            graduation_date='2008-10-28',
                            institution='Escola de pilotagem de Rio Branco')

        instr5 = Instructor(name='Acácio',
                            license_number=7894561,
                            address='Rua das nações, 404',
                            birth_date='1987-9-9',
                            course_name='Pilotagem comercial',
                            graduation_date='2017-8-16',
                            institution='Escola holandesa de aviação civil')

    commit()
예제 #20
0
def show_student():
    for obj in Student.get_all_obj_list():
        print('\033[33;1m [%s][%s]校区  班级[%s] 学生[%s] \033[0m'.center(60, '-') \
              % (obj.classes_nid.get_obj_by_nid().school_nid.get_obj_by_nid().name,
                 obj.classes_nid.get_obj_by_nid().school_nid.get_obj_by_nid().addr,
                 obj.classes_nid.get_obj_by_nid().name, obj.name))
예제 #21
0
def get_students_list():
    '''Retorna uma lista de dicts com informções de cada aluno'''

    students = Student.select()
    schema = StudentSchema(many=True)
    return schema.dump(list(students)).data
예제 #22
0
def show_student():
    for obj in Student.get_all_obj_list():
        print('\033[33;1m学生 名字[%s] 年龄[%s] qq[%s] 班级[%s] \033[0m'\
              % (obj['name'],obj['age'],obj['qq'],\
                 obj['classes_nid'].get_obj_by_uuid(settings.CLASSES_DB_DIR)['name']))
예제 #23
0
def main(args):
    """ Iterate through assistants and scrap their moodle """
    if len(args) < 1:
        todos = Assistant.objects.all()
    else:
        todos = []
        for a in args[1:]:
            try:
                assistant = Assistant.objects.get(pk=int(a))
                todos.append(assistant)
            except: 
                sys.stderr.write('Could not load assistant: %s' % a)
    
    # Execute todos
    for a in todos:
        if not a.is_updater:
            continue
        
        session = MoodleSession(str(a.moodle_url))
        session.set_verbosity(0)
        try:
            session.login(a.moodle_user, a.moodle_password)
        except LoginError:
            sys.stderr.write("Failed to connect.\n")
            sys.exit(1)
        
        if not session.answered("Overview of my courses"):
            sys.stderr.write("Unexpected page (%d bytes)\n" % len(session.body()))
            sys.exit(-2)
        else:
            course_id = int(a.moodle_course_id)
            try:
                course = Course.objects.get(external_id=course_id)
            except:
                courses = session.list_courses()
                course = None
                for c in courses:
                    if c[0] == course_id:
                        course = Course(external_id=course_id, title=c[1], name=''.join([chr[0] for chr in c[1].split(' ')]))
                        course.save()
                        break
                if course is None:
                    sys.stderr.write("Could not get course: %d " % course_id)
                    continue
                
            groups = session.list_groups(int(a.moodle_course_id))
            
            for key,g in groups.items():
                for user in g['users']:
                    try:
                        student = Student.objects.get(external_id=user[0])
                    except:
                        student = Student(external_id=user[0])
                        
                    if student.first_name != user[1] or \
                        student.avatar != user[2] or \
                        student.group != g['name']:
                            student.first_name = user[1]
                            student.avatar = user[2]
                            student.group = g['name']
                            student.save()
                            
                    if course.students.filter(id=student.id).count() == 0:
                        # Add student to course
                        course.students.add(student)
            # Assign the current assistant to the newly created course:
            a.courses.add(course)
            
            print "Updated course: ", a.moodle_course_id, " for ", a
예제 #24
0
def main(args):
    """ Iterate through assistants and scrap their moodle """
    if len(args) < 1:
        todos = Assistant.objects.all()
    else:
        todos = []
        for a in args[1:]:
            try:
                assistant = Assistant.objects.get(pk=int(a))
                todos.append(assistant)
            except:
                sys.stderr.write('Could not load assistant: %s' % a)

    # Execute todos
    for a in todos:
        if not a.is_updater:
            continue

        session = MoodleSession(str(a.moodle_url))
        session.set_verbosity(0)
        try:
            session.login(a.moodle_user, a.moodle_password)
        except LoginError:
            sys.stderr.write("Failed to connect.\n")
            sys.exit(1)

        if not session.answered("Overview of my courses"):
            sys.stderr.write("Unexpected page (%d bytes)\n" %
                             len(session.body()))
            sys.exit(-2)
        else:
            course_id = int(a.moodle_course_id)
            try:
                course = Course.objects.get(external_id=course_id)
            except:
                courses = session.list_courses()
                course = None
                for c in courses:
                    if c[0] == course_id:
                        course = Course(
                            external_id=course_id,
                            title=c[1],
                            name=''.join([chr[0] for chr in c[1].split(' ')]))
                        course.save()
                        break
                if course is None:
                    sys.stderr.write("Could not get course: %d " % course_id)
                    continue

            groups = session.list_groups(int(a.moodle_course_id))

            for key, g in groups.items():
                for user in g['users']:
                    try:
                        student = Student.objects.get(external_id=user[0])
                    except:
                        student = Student(external_id=user[0])

                    if student.first_name != user[1] or \
                        student.avatar != user[2] or \
                        student.group != g['name']:
                        student.first_name = user[1]
                        student.avatar = user[2]
                        student.group = g['name']
                        student.save()

                    if course.students.filter(id=student.id).count() == 0:
                        # Add student to course
                        course.students.add(student)
            # Assign the current assistant to the newly created course:
            a.courses.add(course)

            print "Updated course: ", a.moodle_course_id, " for ", a