Exemple #1
0
    def post():
        data = request.get_json()
        schema = {'type': 'object',
                  'properties': {'education_id': {'type': 'integer'},
                                 'name': {'type': 'string'},
                                 'description': {'type': 'string'}}}

        try:
            validictory.validate(data, schema)
        except Exception:
            return make_api_response(400,
                                     'Data does not correspond to scheme.')

        if Education.query\
                .filter(Education.id == data['education_id']).count() == 0:
            return make_api_response(400, 'No object has been associated with '
                                     'the education ID that has been '
                                     'specified.')

        if Course.query.filter(Course.name == data['name']).count() > 0:
            return make_api_response(400, 'There is already an object with '
                                     'the name that has been specified.')

        course = Course(data['name'], data['description'])
        db.session.add(course)
        db.session.commit()

        return course.to_dict(), '201 The object has been created.'
Exemple #2
0
def add_cou(request):
    names = ['大学英语', '大学语文', '高数', '模电', 'VHDL']
    for name in names:
        cou = Course()
        cou.c_name = name
        cou.save()
    return HttpResponse('添加课程成功')
Exemple #3
0
 def test_03_get_all(self):
     course = Course.add({"name": "Curso de teste"})
     courses = Course.get_by_filter("all")
     assert list(courses[0].keys()) == [
         'id', 'name', 'number_of_videos', 'duration', 'price',
         'is_watchable'
     ]
Exemple #4
0
def create_course():
    from random import choice
    from string import ascii_uppercase as uc, digits as dg

    course_name = request.values['course_name']
    part1 = ''.join(choice(uc) for j in range(3))  # 三个大写的英文
    part2 = ''.join(choice(dg) for j in range(3))  # 三个随机数字
    invitation_code = part1 + part2
    search_result = Course.query.filter_by(id=invitation_code).first()

    while search_result is not None:
        part1 = ''.join(choice(uc) for j in range(3))  # 三个大写的英文
        part2 = ''.join(choice(dg) for j in range(3))  # 三个随机数字
        invitation_code = part1 + part2

    newcourse = Course(invitation_code, course_name, g.user.id)
    user = User.query.filter_by(id=g.user.id).first()
    newcourse.creator = user

    db.session.add(newcourse)
    db.session.commit()

    result = session['result']
    result.append((url_for('t_class_section',
                           course_id=invitation_code), course_name))
    session.pop('result', None)
    session['result'] = result

    return jsonify(invitation_code)
def import_professors(df):
    for i in tqdm(df.iterrows()):
        pid, series = i
        pname = series.Name
        score = None if str(series.Score) == 'nan' else series.Score
        nrev = None if str(series.Num_Reviews) == 'nan' else series.Num_Reviews
        if series.Nugget == 'None':
            nuggets = None
        elif series.Nugget == 'Gold':
            nuggets = 1
        else:
            nuggets = 0
        p = Professor(pid=pid,
                      pname=pname,
                      nuggets=nuggets,
                      score=score,
                      nrev=nrev)

        dparsed = ast.literal_eval(series.Dept)
        if dparsed:
            if isinstance(dparsed, list):
                for d in dparsed:
                    dname, did = d
                    dquery = Department.query.filter(
                        Department.did == did).first()
                    if dquery:
                        p.departments.append(dquery)
                    else:
                        d = Department(dname=dname, did=did)
                        p.departments.append(d)
            else:
                dname, did = dparsed
                dquery = Department.query.filter(Department.did == did).first()
                if dquery:
                    p.departments.append(dquery)
                else:
                    d = Department(dname=dname, did=did)
                    p.departments.append(d)

        cparsed = ast.literal_eval(series.Courses)
        if cparsed:
            if isinstance(cparsed, list):
                for c in cparsed:
                    cname, cid = c
                    cquery = Course.query.filter(Course.cid == cid).first()
                    if cquery:
                        p.courses.append(cquery)
                    else:
                        c = Course(cname=cname, cid=cid)
                        p.courses.append(c)
            else:
                cname, cid = cparsed
                cquery = Course.query.filter(Course.cid == cid).first()
                if cquery:
                    p.courses.append(cquery)
                else:
                    c = Course(cname=cname, cid=cid)
                    p.courses.append(c)
        db.session.add(p)
        db.session.commit()
def add_course(request):
    c_names = ['大学英语', '商务英语', '线代', '高数']
    for name in c_names:
        c = Course()
        c.c_name = name
        c.save()
    return HttpResponse('创建课程成功')
Exemple #7
0
    def test_course_with_class(self):
        # + 原课程
        raw_course = RawCourse(name=u'Java')
        db.session.add(raw_course)
        db.session.commit()
        # + 从原课程指定实际课程
        course = Course(User(name=u"老师"), RawCourse(name=u"没课"))
        # course.raw_course_id = raw_course.id
        course.raw_course = raw_course
        db.session.add(course)
        db.session.commit()
        # + 两个班级
        c = _Class(name=u'14计本1')
        c2 = _Class(name=u'14计本2')
        # 将班级与课程关联起来
        c.courses.append(course)
        # c2.courses.append(course)
        course.classes.append(c2)
        db.session.add(c)
        db.session.add(c2)
        db.session.commit()

        # 判断
        self.assertTrue(course in c.courses)
        self.assertTrue(c in course.classes)
        self.assertTrue(course in c2.courses)
        self.assertTrue(c2 in course.classes)
        course.classes.remove(c)
        db.session.add(course)
        db.session.commit()
        self.assertFalse(course in c.courses)
        self.assertFalse(c in course.classes)
Exemple #8
0
    def add_course(id):
        teacher = Teacher.query.filter_by(id=id).first()
        courseName = str(request.data.get('courseName', ''))
        author = teacher.firstname
        limit = str(request.data.get('limit', ''))

        if courseName and author and limit:
            new_course = Course(courseName=courseName,
                                author=author,
                                limit=limit)
            teacher.course_teachers.append(new_course)
            teacher.save()
            new_course.save()
            response = jsonify({
                'id': new_course.id,
                'courseName': new_course.courseName,
                'author': new_course.author,
                'limit': new_course.limit,
                'students': new_course.course_students
            })
            response.status_code = 201
            return response
        else:
            return {
                "ERROR": "Введіть всі поля courseName and author and limit",
                "STATUS CODE": 405
            }
Exemple #9
0
def update(baseName):
    oldDF = models.Course.query.all()
    #oldIDs = models.Course.query.session_ID()
    newDF = json.load(
        open(app.config["FILE_UPLOADS"] + '/' + baseName + ".json", "r"))
    oldSessionIDs = []
    for oldRecord in oldDF:
        oldSessionIDs.append(oldRecord.session_ID)
    for oldRecord in oldDF:
        for newRecord in newDF:
            if oldRecord.session_ID == newRecord[
                    'SessionID'] and oldRecord != newRecord:
                db.session.delete(oldRecord)
                alternate = Course(Course_title=newRecord['CourseTitle'],
                                   Classroom=newRecord['Classroom'],
                                   Course_code=newRecord['CourseCode'],
                                   Credits=newRecord['Cr'],
                                   Format=newRecord['CourseFormat'],
                                   session_ID=newRecord['SessionID'])
                db.session.add(alternate)
                db.session.commit()
            elif not (newRecord['SessionID'] in oldSessionIDs):  # in oldIDs

                new = Course(Course_title=newRecord['CourseTitle'],
                             Classroom=newRecord['Classroom'],
                             Course_code=newRecord['CourseCode'],
                             Credits=newRecord['Cr'],
                             Format=newRecord['CourseFormat'],
                             session_ID=newRecord['SessionID'])
                db.session.add(new)
                db.session.commit()
Exemple #10
0
def add_cou():
    cous = ['线代', '高数', '概论', '大学物理', '大学英语']
    for cou in cous:
        c = Course()
        c.c_name = cou
        c.save()
    return '创建课程成功'
def __add_default_courses(app: Flask):
    app.app_context().push()
    db.create_all()
    if Course.query.count() == 0:

        course = Course(
            "course1",
            datetime.strptime("2021-01-01", "%Y-%m-%d").date(),
            datetime.strptime("2021-01-01", "%Y-%m-%d").date(),
            1,
        )
        db.session.add(course)

        course2 = Course(
            "course2",
            datetime.strptime("2019-01-01", "%Y-%m-%d").date(),
            datetime.strptime("2019-01-01", "%Y-%m-%d").date(),
            2,
        )
        db.session.add(course2)

        course3 = Course(
            "course3",
            datetime.strptime("2018-01-01", "%Y-%m-%d").date(),
            datetime.strptime("2018-01-01", "%Y-%m-%d").date(),
            3,
        )
        db.session.add(course3)

        db.session.commit()
Exemple #12
0
def courses(filter):
    if request.method == 'POST':
        json_args = request.form['json_args']
        result = json.loads(json_args)
        while type(result) == str:
            result = json.loads(result)
        if request.files:
            thumbnail = request.files.get('thumbnail')
            result['thumbnail'] = thumbnail.read()
        if is_valid_admin(request):
            course = Course.add(result)
            if course:
                course_dict = course.as_dict()
                response = jsonify(course_dict)
                response.status_code = 200
                return response
            return error_response('Falha na adição do curso', 500)
        else:
            return error_response('Permissão negada', 401)
    elif request.method == 'GET':
        courses = Course.get_by_filter(filter)
        if courses is not None:
            response = jsonify(courses)
            response.status_code = 200
            return response
        return error_response('Não foi possível recuperar os cursos', 500)
Exemple #13
0
def course(id):
    course = Course.get_by_id(id)
    if course is None:
        return {}, 404
    if request.method == 'GET':
        course_dict = course.as_dict()
        response = jsonify(course_dict)
        response.status_code = 200
        return response
    if is_valid_admin(request):
        if request.method == 'PUT':
            json_args = request.form['json_args']
            result = json.loads(json_args)
            while type(result) == str:
                result = json.loads(result)
            course = Course.update_data(id, result)
            if course:
                course_dict = course.as_dict()
                response = jsonify(course_dict)
                response.status_code = 200
                return response
            else:
                return error_response('Curso não atualizado', 500)

        elif request.method == 'DELETE':
            if Course.delete(id):
                return {}, 200
            else:
                return error_response(
                    'Curso não deletado. Tente novamente em alguns minutos.',
                    500)
    else:
        return error_response('Permissão negada', 401)
Exemple #14
0
def postTaPosition():
    form = PositionPostForm()
    if request.method == 'POST':
        if form.validate_on_submit():
            post = PositionPost(course=request.form['course'],
                                semester=request.form['semester'],
                                numbersOfTA=request.form['numbersOfTA'],
                                minGPA=request.form['minGPA'],
                                minGrade=request.form['minGrade'],
                                requirements=request.form['requirements'],
                                instructor_id=current_user.instructor.id)
            course = Course(name=post.course,
                            numbersOfTA=post.numbersOfTA,
                            instructor_id=current_user.instructor.id)
            course.currentTA = 0
            post.name = current_user.instructor.name
            post.phone = current_user.instructor.phone
            post.classes = course
            db.session.add(course)
            db.session.add(post)
            current_user.instructor.courses.append(course)
            current_user.instructor.posts.append(post)
            db.session.commit()
            flash('Posted')
            return redirect('/instructor')
    return render_template('create.html', title="Post TA-Positions", form=form)
Exemple #15
0
def add_cou(request):
    cous = ['线代', '高数', '物理', '英语']
    for c in cous:
        cou = Course()
        cou.c_name = c
        cou.save()
    return HttpResponse('创建课程成功')
Exemple #16
0
def add_course():
    cou = Course()
    cou.c_name = '大学英语'
    db.session.add(cou)
    db.session.commit()

    return '创建成功'
Exemple #17
0
def add_courses(num_courses=12):
    course_titles = [
        'CS', 'ARCH', 'EAS', 'MECH', 'BIOL', 'BMED', 'ECE', 'HTS', 'LMC'
    ]
    designations = [d['name'] for d in Designation.get_all()]
    categories = [c['name'] for c in Category.get_all()]

    for i in xrange(num_courses):
        course_number = '{} {}'.format(
            course_titles[randint(0,
                                  len(course_titles) - 1)],
            randint(1000, 9999))
        instructor = 'Instructor for {}'.format(course_number)
        designation = designations[randint(0, len(designations) - 1)]
        cats = [
            categories[i]
            for i in sample(xrange(len(categories)), randint(2, 5))
        ]
        new_course = Course(course_number=course_number,
                            name='Course Name for {}'.format(course_number),
                            instructor=instructor,
                            est_num_students=randint(0, 1000),
                            designation_name=designation,
                            categories=cats,
                            is_new_course=True)
        new_course.save()
Exemple #18
0
 def test_03_get_videos_as_dict(self):
     course = Course.add({'name': "Curso de Teste"})
     course = Course.get_by_id(1)
     video = Video.add(1, {'youtube_code': 'test_code', 'course_order': 1})
     videos = course.get_videos_as_dict()
     assert list(videos[0].keys()) == ['id', 'youtube_code', 'title', \
         'description', 'duration', 'thumbnail', 'course_order'] and videos[0]['youtube_code'] == 'test_code'
Exemple #19
0
 def test_07_update_data_fail(self):
     course = Course.add({"name": "Curso de teste"})
     updated_course = Course.update_data(
         2, {"name": "Curso de teste atualizado"})
     updated_course_2 = Course.update_data(
         1, {"error": "Curso de teste não atualizado"})
     assert updated_course is None and updated_course_2 is None
Exemple #20
0
 def test_05_get_with_search(self):
     course = Course.add({
         "name": "Curso de teste",
         "expires_at": "2020-11-20"
     })
     course = Course.add({"name": "Batata", "expires_at": "4020-12-10"})
     courses = Course.get_by_filter("Batata")
     assert len(courses) == 1 and courses[0]['name'] == "Batata"
Exemple #21
0
 def test_06_get_with_multiple_word_search(self):
     course = Course.add({
         "name": "Fisioterapia para velhinhos",
         "expires_at": "2020-11-20"
     })
     course = Course.add({"name": "Batata", "expires_at": "4020-12-10"})
     courses = Course.get_by_filter("Fisioterapia%20velhinhos")
     assert len(courses) == 1 and courses[0][
         'name'] == "Fisioterapia para velhinhos"
Exemple #22
0
def create_todo():
    a1 = Course(title='Mathematics')
    b1 = Todo(description='Finish math homework', course=a1)
    db.session.add(b1)

    a2 = Course(title='English')
    b2 = Todo(description='write essay', course=a2)
    db.session.add(b2)
    db.session.commit()
Exemple #23
0
def add_course():
    if request.method == 'GET':
        courses = ['线代', '高数', '大学物理', '计算机', '英语']
        for course in courses:
            c = Course()
            c.c_name = course
            db.session.add(c)
        db.session.commit()
        return '创建课程成功'
Exemple #24
0
def seedTheCourseData():
    courses = [
        "Broadmoor", "Camas Meadows", "Colwood", "Heron Lakes Great Blue",
        "Heron Lakes Greenback", "Tri Mountain"
    ]

    for course in courses:
        new_course = Course(name=course)
        new_course.save()
def create_course():
    form = CourseCreationForm()# pragma: no cover
    if form.validate_on_submit():# pragma: no cover
        course = Course(course_code=form.course_code.data,name=form.name.data,venue=form.venue.data,start_time=form.start_time.data,end_time=form.end_time.data,\
            day=form.day.data, key=form.key.data, number_of_tutors=form.number_of_tutors.data, lecturer=current_user.lecture)
        course.lecturer = current_user.lecture
        db.session.add(course)
        db.session.commit()
        return redirect(url_for('courses.my_courses'))
    return render_template('courses/create_course.html',title='Create a course',form=form)# pragma: no cover
Exemple #26
0
 def getCourseInfo(self, courseName):
     db = SqliteReader(self.Options.DatabasePath)
     row = db.find_one('''SELECT Name, Title, HasTranscript
                             FROM Course
                             WHERE Name = ?''', [courseName])
     course = Course(name=row[0], title=row[1], has_trans=row[2])
     course.Modules = self.getModulesFromDb(db, courseName)
     #print(course.CourseName,': ', course.CourseTitle)
     db.close()
     return course
Exemple #27
0
def reset_db():
    flash('Resetting Database: deleting old data and repopulating with dummy data')
    # clear all data from all tables
    meta = db.metadata
    for table in reversed(meta.sorted_tables):
        print('Clear table {}'.format(table))
        db.session.execute(table.delete())
    db.session.commit()

    # populate tables with dummy data
    users = [
        User(username='******', name='Professor Pancake', email='*****@*****.**', bio='Not a professor, definitely a pancake'),
        User(username='******', name='Mouse Cop', email='*****@*****.**', bio='Cat no like mouse. Cat like coding WORM'),
        User(username='******', name='Little Russian Lady', email='*****@*****.**', bio='Please... get me some beets'),
    ]
    users[0].set_password('cat1')
    users[1].set_password('cat2')
    users[2].set_password('cat3')

    db.session.add_all(users)
    db.session.commit()

    users[0].send_request(users[2])
    users[1].send_request(users[0])
    users[2].send_request(users[1])


    departments = [
        Department(name='Computer Science', abbr='COMP'),
        Department(name='Languages', abbr='LNGS'),
        Department(name='Mathematics', abbr='MATH')
    ]
    db.session.add_all(departments)

    courses = [
        Course(name='Principles of Computer Science II', number=172, department=departments[0]),
        Course(name='Introduction to Data Structures', number=220, department=departments[0]),
        Course(name='Language and the Mind', number=242, department=departments[1]),
        Course(name='Statistics', number=124, department=departments[2]),
        Course(name='Intro to WORM Programming', number=999, department=departments[0]),
    ]
    db.session.add_all(courses)

    associations = [
        MentorToCourse(mentor=users[0], course=courses[1]),
        MentorToCourse(mentor=users[0], course=courses[0]),
        MentorToCourse(mentor=users[1], course=courses[3]),
        MentorToCourse(mentor=users[1], course=courses[4]),
        MentorToCourse(mentor=users[2], course=courses[2]),
    ]
    db.session.add_all(associations)

    db.session.commit()

    return redirect(url_for('index'))
Exemple #28
0
 def test_05_get_active(self):
     course = Course.add({
         "name": "Curso de teste",
         "expires_at": "2020-11-20"
     })
     course = Course.add({
         "name": "Curso de teste 2",
         "expires_at": "4020-12-10"
     })
     courses = Course.get_by_filter("active")
     assert len(courses) == 1 and courses[0]['name'] == "Curso de teste 2"
Exemple #29
0
def add_todo():
    a1 = Course(title='Drafting')
    b1 = Todo(
        description='start blueprints',
        course=a1
    )
    db.session.add(b1)

    a2 = Course(title='Python')
    b2 = Todo(description='practice', todo=a2)
    db.session.add(b2)
    db.session.commit()
Exemple #30
0
def create():
    # TODO authenticate user
    form = CreateCourseForm()
    if form.validate_on_submit():
        course = Course(number=int(form.courseNumber.data),
                        name=form.courseName.data,
                        description=form.courseDescription.data,
                        prerequisites=form.coursePrereqs.data,
                        building=form.courseBuilding.data,
                        room=form.courseRoomNo.data)

        course.setVersion()
        course.is_core = form.isCore.data
        course.is_diversity = form.isDiversity.data
        course.is_elr = form.isELR.data
        course.is_wi = form.isWI.data

        syllabus = Syllabus(course_number=form.courseNumber.data,
                            course_version=course.version,
                            semester=form.semester.data,
                            year=form.year.data,
                            section=form.section.data)
        syllabus.setVersion()

        db.session.add(syllabus)
        db.session.add(course)
        db.session.commit()
        # TODO: Handle case, what if course already exists. crash cleanly
        flash("Course Created!")
    return render_template('course/create.html',
                           title="Create Course",
                           form=form)
Exemple #31
0
def store(request):
    # Create a new Course
    course = Course()
    course.name = request.POST['name']
    course.save()

    # A course belong to a user
    userCourse = UserCourse()
    userCourse.course = course
    userCourse.user = request.user
    userCourse.save()

    # Redirect to the see view
    return redirect('courses')
Exemple #32
0
    def test_can_view_students(self):
        user = UserFactory.create()
        self.client.login(username=user.username, password='******')
        parent = ParentFactory()
        parent.users.add(user)
        stu1 = StudentFactory.create(parent=parent)
        stu2 = StudentFactory.create(parent=parent)
        course1 = Course(name='Python')
        course1.save()
        stu1.wants_courses.add(course1)

        response = self.client.get(reverse('students') + '?wants=%i' % course1.id)
        self.assertEqual(200, response.status_code)

        soup = BeautifulSoup(response.content, 'html.parser')
        text = soup.get_text()
        self.assertIn(stu1.name, text)
        self.assertNotIn(stu2.name, text)
Exemple #33
0
def get_course(col_num):

    course_info = table_col(col_num)
    course = Course()
    # course_classify_name = course_info[0]
    course.classify = course_info[0]
    course.topic = course_info[1]
    course.teacher = course_info[2]
    course.introduction = course_info[3]
    course.form = course_info[4]
    course.frequency = course_info[5]
    course.dispass = course_info[6]
    return course
Exemple #34
0
    def test_email_goes_to_right_parents(self):
        user1 = UserFactory.create()
        self.client.login(username=user1.username, password='******')
        parent1 = ParentFactory()
        parent1.users.add(user1)
        stu1a = StudentFactory.create(parent=parent1)
        stu1b = StudentFactory.create(parent=parent1)

        user2 = UserFactory.create()
        self.client.login(username=user2.username, password='******')
        parent2 = ParentFactory()
        parent2.users.add(user2)
        stu2a = StudentFactory.create(parent=parent2)
        stu2b = StudentFactory.create(parent=parent2)

        course1 = Course(name='Python')
        course1.save()
        stu1a.wants_courses.add(course1)
        py_sec = SectionFactory(course=course1)
        
        parents = email_parents(())  # No filters, so all parents should be included
        self.assertIn(parent1, parents)
        self.assertIn(parent2, parents)

        parents = email_parents((), send_only_upcoming=True)  # No parents have students in upcoming sections
        self.assertNotIn(parent1, parents)
        self.assertNotIn(parent2, parents)

        StudentSectionAssignment(student=stu1a, section=py_sec, status=SS_STATUS_APPLIED).save()

        parents = email_parents((), send_only_upcoming=True)  # parent1 now has a student in an upcoming section
        self.assertIn(parent1, parents)
        self.assertNotIn(parent2, parents)

        parents = email_parents((), send_only_wanted_upcoming=True)
        self.assertNotIn(parent1, parents)
        self.assertNotIn(parent2, parents)

        parents = email_parents((course1.id,), send_only_wanted_upcoming=True)
        self.assertIn(parent1, parents)
        self.assertNotIn(parent2, parents)
import sys
sys.path.append('..')  # fix import directory

from app.models import Course

course = Course(cno='1111',name='diandonglixue')
course = course.save()
print(course.id)