コード例 #1
0
def create_lesson():
    data = request.get_json() or {}
    print("create lesson called")
    if 'title' not in data or 'content' not in data:
        return bad_request('must include title and content')
    if Lesson.query.filter_by(title=data['title']).first():
        return bad_request("there is already a lesson with that title")


#    if data['prev']:
#        previous = Lesson.query.filter_by(id=data['prev']).first()
#        if previous.next:
#            return bad_request('there is already a lesson after lesson {}, namely {}'.format(previous.id, previous.next))

    lesson = Lesson()
    lesson.from_dict(data)
    db.session.add(lesson)
    #    if data['prev'] and not previous.next:
    #            setattr(previous, next, data['id'])
    db.session.commit()
    #handle_lesson()
    response = jsonify(lesson.to_dict())
    response.status_code = 201
    print(lesson.id)
    response.headers['Location'] = url_for('api.get_lesson', id=lesson.id)
    return response
コード例 #2
0
def deploy():
    '''Run deployment tasks'''
    # migrate database to latest revision
    from flask_migrate import upgrade
    upgrade()

    verbose = False
    if app.debug:
        verbose_mode = input('Run in verbose mode? [yes/No]: ')
        if verbose_mode.lower() in ['y', 'yes']:
            verbose = True

    # insert data
    data = 'common'

    from app.models import Permission
    Permission.insert_entries(data=data, verbose=verbose)

    from app.models import Role
    Role.insert_entries(data=data, verbose=verbose)

    from app.models import Room
    Room.insert_entries(data=data, verbose=verbose)

    from app.models import DeviceType
    DeviceType.insert_entries(data=data, verbose=verbose)

    from app.models import LessonType
    LessonType.insert_entries(data=data, verbose=verbose)

    from app.models import Lesson
    Lesson.insert_entries(data=data, verbose=verbose)

    from app.models import Video
    Video.insert_entries(data=data, verbose=verbose)

    data = input(
        'Enter data identifier (e.g.: 20180805 or press the enter/return key for initial data): '
    )
    if data == '':
        data = 'initial'
    datadir = os.path.join(app.config['DATA_DIR'], data)
    if os.path.exists(datadir):
        from app.models import User
        User.insert_entries(data=data, verbose=verbose)

        from app.models import Punch
        Punch.insert_entries(data=data, verbose=verbose)

        from app.models import Device
        Device.insert_entries(data=data, verbose=verbose)

        from app.models import DeviceLessonType
        DeviceLessonType.insert_entries(data=data, verbose=verbose)

        from app.models import UserLog
        UserLog.insert_entries(data=data, verbose=verbose)
コード例 #3
0
ファイル: test_lesson_model.py プロジェクト: amanya/backdne
 def test_to_json(self):
     l = Lesson()
     db.session.add(l)
     db.session.commit()
     json_ = l.to_json()
     expected_keys = [
         'id', 'user_id', 'lesson', 'total_pages_viewed', 'clicks_forward',
         'clicks_backward', 'clicks_menu', 'clicks_lesson_repeat',
         'way_exit', 'is_finished', 'time', 'created'
     ]
     self.assertEqual(sorted(json_.keys()), sorted(expected_keys))
コード例 #4
0
def create_lesson(course_id, section_id):
    form = CreateLessonForm()
    form["csrf_token"].data = request.cookies["csrf_token"]

    if form.validate_on_submit():
        data = request.get_json()
        new_lesson = Lesson(title=form.data['title'],
                            content_media_type=form.data['content_media_type'],
                            content=form.data['content'],
                            is_complete=form.data['is_complete'],
                            section_id=section_id)
        db.session.add(new_lesson)
        db.session.commit()
        return new_lesson.to_dict()
    return {'errors': form_errors(form.errors)}
コード例 #5
0
ファイル: utils.py プロジェクト: qwert2603/crmit
def group_attendings_percent_by_month_dict(group_id):
    group = Group.query.get(group_id)
    result = dict()
    for month_number in range(group.start_month, group.end_month + 1):
        students_in_month = group.students_in_month(month_number).count()
        if students_in_month == 0 or Lesson.lessons_in_group_in_month(
                group_id, month_number).count() == 0:
            continue
        was_count = 0
        lessons = Lesson.lessons_in_group_in_month(group_id,
                                                   month_number).all()
        for l in lessons:
            was_count += l.attendings_was.count()
        result[month_number] = 100 * was_count // (students_in_month *
                                                   len(lessons))
    return result
コード例 #6
0
def lesson(base, slug):
    if base and slug:
        lessons = Lesson.search([('course.slug', '=', base),
                                 ('slug', '=', slug)])
        if len(lessons) == 1:
            form = LessonCommentForm()
            comments = LessonComment.search([('lesson', '=', lessons[0].id)],
                                            order=[('id', 'DESC')])

            defaults = {}
            defaults['lessons'] = lessons
            defaults['course'] = base
            defaults['form'] = form
            if current_user.is_authenticated:
                user = User(current_user)
                defaults['user'] = user

            if len(comments) > 0:
                defaults['comments'] = comments
            else:
                defaults['comments'] = []

            if form.validate_on_submit() and current_user.is_authenticated:
                content = form.comment_content.data
                user = User(current_user)
                comment, = LessonComment.create([{
                    'content': content,
                    'user': user.id,
                    'lesson': lessons[0].id,
                }])
                #defaults['comments'].append(comment)
                #return render_template('course/lesson.html', **defaults)
                return redirect(url_for('course.lesson', base=base, slug=slug))
            courses = []
            courses.append(lessons[0].course.service.id)
            courses.append(lessons[0].course.yearly_service.id)
            with Transaction().set_context(courses=courses):
                if lessons[0].membership_type == 'free':
                    return render_template('course/lesson.html', **defaults)
                elif lessons[0].membership_type == 'premium' and \
                        current_user.is_authenticated:
                    user = User(current_user)
                    if user.active_membership:
                        return render_template('course/lesson.html',
                                               **defaults)
                    else:
                        return redirect(
                            url_for('course.enroll',
                                    course=lessons[0].course.id))
                elif lessons[0].membership_type == 'premium' and \
                        not current_user.is_authenticated:
                    return redirect(url_for('auth.login', next=request.url))
                else:
                    return redirect(
                        url_for('course.enroll', course=lessons[0].course.id))
    #if type(current_user) == 'AnonymousUserMixin':
    if not isinstance(current_user, int):
        return redirect(url_for('auth.login', next=request.url))
    user = User(current_user)
    return render_template('404.html', user=user), 404
コード例 #7
0
ファイル: utils.py プロジェクト: qwert2603/crmit
def lessons_lists(group_id, month_number):
    lessons = Lesson.lessons_in_group_in_month(group_id, month_number) \
        .order_by(Lesson.date) \
        .all()
    attendings_states = dict()
    for l in lessons:
        attendings_states[l.id] = dict()
        for a in l.attendings:
            attendings_states[l.id][a.student_id] = a.state
    return [lessons, attendings_states]
コード例 #8
0
ファイル: routes.py プロジェクト: Siequnu/flask-classes
def create_lesson(class_id):
    if current_user.is_authenticated and app.models.is_admin(current_user.username):
        turma = Turma.query.get(class_id)

        # Check if current user is registered as a class manager
        if app.classes.models.check_if_turma_id_belongs_to_a_teacher (turma.id, current_user.id) is False:
            abort (403)

        form = LessonForm(start_time = turma.lesson_start_time,
                          end_time = turma.lesson_end_time,
                          date = datetime.datetime.now())
        del form.edit
        if form.validate_on_submit():
            # Extract lesson data from pasted Zoom message
            meeting_url = ''
            meeting_id = ''
            meeting_passcode = ''

            try:

                if form.online_lesson_invitation.data:
                    split = form.online_lesson_invitation.data.split('Meeting ID: ')
                    split = split[1].split ('\n')
                    meeting_details = split[0].split(' Passcode: ')
                    meeting_id = meeting_details[0]
                    meeting_passcode = meeting_details[1]

                    meeting_url = form.online_lesson_invitation.data.split('Join Zoom Meeting ')
                    meeting_url = meeting_url[1].split('  Meeting ID:')
                    meeting_url = meeting_url[0]

                # Overwrite auto-generated details if these were given
                if form.online_lesson_code.data:
                    meeting_id = form.online_lesson_code.data

                if form.online_lesson_password.data:
                    meeting_passcode = form.online_lesson_password.data
            except:
                flash ('An error occured while parsing the Zoom invitation. The lesson has been created without a Zoom code.')

            lesson = Lesson(start_time = form.start_time.data,
                            end_time = form.end_time.data,
                            online_lesson_code = meeting_id,
                              online_lesson_password = meeting_passcode,
                            online_lesson_url = meeting_url,
                            date = form.date.data,
                            turma_id = turma.id)
            db.session.add(lesson)
            db.session.commit()
            flash ('New lesson added for ' + turma.turma_label + '.', 'success')
            return redirect (url_for('classes.class_attendance', class_id = turma.id))
        return render_template('classes/lesson_form.html', title='Create lesson', turma = turma, form = form)
    abort (403)
コード例 #9
0
    def test_get_finished_lessons(self):
        # add a user
        u = User(username='******',
                 password='******',
                 confirmed=True,
                 role=Role.get('Administrator'))
        db.session.add(u)
        db.session.commit()

        ls = [
            Lesson(lesson="lesson1", user_id=u.id, is_finished=False),
            Lesson(lesson="lesson1", user_id=u.id, is_finished=False),
            Lesson(lesson="lesson2", user_id=u.id, is_finished=False),
            Lesson(lesson="lesson2", user_id=u.id, is_finished=True),
            Lesson(lesson="lesson3", user_id=u.id, is_finished=True),
            Lesson(lesson="lesson3", user_id=u.id, is_finished=True)
        ]

        for l in ls:
            db.session.add(l)

        db.session.commit()

        response = self.client.get(url_for('api.get_finished_lessons'),
                                   headers=self.get_api_headers('john', 'cat'))
        self.assertTrue(response.status_code == 200)
        json_response = json.loads(response.data.decode('utf-8'))

        expected = {
            "lesson1": False,
            "lesson2": True,
            "lesson3": True,
        }

        self.assertEqual(json_response, expected)
コード例 #10
0
def add_schedule():
    data = request.get_json()
    print(data)
    message = None
    success = True

    if data and len(data):
        try:
            group = data['groupname']
            date = data['date']
            order = data['order']
            auditory = data['auditory']
            teacher = data['teacher']['name']
            teacher_surname = data['teacher']['surname']
            teacher_patronymic = data['teacher']['patronymic']
            subject_title = data['subject']['title']
            subject_type = data['subject']['subj_type']

            group = Group.query.filter_by(name=group).first()
            teacher = utils.get_teacher(teacher, teacher_surname,
                                        teacher_patronymic)
            subject = utils.get_subject(subject_title, subject_type)

            date = utils.convert_str_to_date(date, '%Y-%m-%d')
            order = int(order)
            lesson = Lesson(date=date,
                            order=order,
                            auditory=auditory,
                            teacher=teacher,
                            group=group,
                            subject=subject)

            db.session.add(lesson)
            db.session.commit()

        except ValueError as ve:
            app.logger.info(ve)
            message = "Incorrect order!"
            success = False
        except KeyError as ke:
            app.logger.info(ke)
            success = False
            message = "Caught empty lesson"
        except SQLAlchemyError as se:
            app.logger.info(se)
            success = False
            message = "Incorrect data or busy lesson for this time"

        return jsonify(success=success, message=message)
    else:
        return render_template('add_schedule.html')
コード例 #11
0
def group_stat(group_id):
    group = Group.query.get_or_404(group_id)
    students_by_month = group_students_count_by_month_dict(group_id)
    pays_by_month = group_payments_count_by_month_dict(group_id)
    pays_confirmed_by_month = group_payments_confirmed_count_by_month_dict(group_id)
    attendings_percent_by_month = group_attendings_percent_by_month_dict(group_id)
    months = [{'month_number': month_number, 'month_name': get_month_name(month_number),
               'students_count': students_by_month.get(month_number),
               'lessons_count': Lesson.lessons_in_group_in_month(group_id, month_number).count(),
               'attendings_percent': attendings_percent_by_month.get(month_number, 0),
               'payments': pays_by_month.get(month_number, 0),
               'payments_confirmed': pays_confirmed_by_month.get(month_number, 0)}
              for month_number in range(group.start_month, group.end_month + 1)]
    return render_template('stat/group.html', group=group, months=months)
コード例 #12
0
ファイル: utils.py プロジェクト: qwert2603/crmit
def fill_group_by_schedule(group, new_dows):
    existing_lessons = group.lessons.filter(
        Lesson.date > datetime.date.today()).all()
    for lesson in existing_lessons:
        for a in lesson.attendings:
            db.session.delete(a)
        db.session.delete(lesson)
    start_date_1 = datetime.date.today() + datetime.timedelta(days=1)
    start_date_2 = start_date_of_month(group.start_month)
    for date in days_of_dows(start_date=max(start_date_1, start_date_2),
                             end_date=end_date_of_month(group.end_month),
                             dows=new_dows):
        db.session.add(
            Lesson(group_id=group.id, teacher_id=group.teacher_id, date=date))
コード例 #13
0
 def post(self):
     json_data = request.get_json()
     if not json_data:
         raise RequestException("No input data", 400)
     try:
         data = lesson_schema.load(json_data)
     except ValidationError as err:
         raise RequestException("Invalid input data", 400, err.messages)
     lesson = Lesson.create(**data)
     result = lesson_schema.dump(lesson)
     response = jsonify({
         APIConst.MESSAGE: 'created new lesson',
         APIConst.DATA: result
     })
     return response
コード例 #14
0
ファイル: hide.py プロジェクト: pykarimov/spbu4u
def hide_lesson(call_back):
    user = g.current_tbot_user

    lesson = Lesson.add_or_get(**nf.get_lesson_data(
        data=call_back.message.text.split("\n\n")[1].split("\n"),
        hide_type=call_back.data))
    if lesson not in user.hidden_lessons:
        user.hidden_lessons.append(lesson)

    db.session.commit()

    bot.edit_message_text(text="Занятие скрыто",
                          chat_id=user.tg_id,
                          message_id=call_back.message.message_id,
                          parse_mode="HTML")
コード例 #15
0
 def patch(self, id):
     lesson = self.get_resource_with_ids(Lesson, id)
     json_data = request.get_json()
     try:
         data = lesson_patch_schema.load(json_data, partial=True)
     except ValidationError as err:
         raise RequestException("Invalid input data", 400, err.messages)
     try:
         lesson.update(**data)
     except Exception as err:
         raise RequestException(
             payload={APIConst.INPUT: json_data}) from err
     result = lesson_schema.dump(Lesson.get_with_id(lesson.id))
     response = jsonify({
         APIConst.MESSAGE: 'updated lesson {}'.format(id),
         APIConst.DATA: result
     })
     return response
コード例 #16
0
ファイル: views.py プロジェクト: qwert2603/crmit
def create_lesson(group_id):
    group = Group.query.get_or_404(group_id)
    if 'submit' in request.form:
        date = parse_date_or_none(request.form.get('date'))
        if date is None or date < start_date_of_month(
                group.start_month) or date > end_date_of_month(
                    group.end_month):
            abort(409)
        if current_user.is_teacher and date < datetime.date.today():
            abort(409)
        db.session.add(
            Lesson(group_id=group_id, teacher_id=group.teacher_id, date=date))
        flash('занятие создано: {}'.format(date))
        return redirect(
            url_for('.lessons_in_month',
                    group_id=group_id,
                    month_number=number_of_month_for_date(date)))
    return render_template('lessons/create_lesson.html', group=group)
コード例 #17
0
def new_course():
    if not current_user.admin: abort(401)

    form = NewCourseForm()
    form.course.choices = [(g.id, g.name)
                           for g in Course.query.order_by('name')]

    if form.validate_on_submit():
        lesson = Lesson(title=form.title.data,
                        body=form.body.data,
                        course_id=form.course.data)
        db.session.add(lesson)
        db.session.commit()

        course = Course.query.get(form.course.data)
        flash('De les is toegevoegd aan de ' + course.name)
        return redirect(url_for('lessons.index'))

    return render_template('lessons/new.html', form=form)
コード例 #18
0
ファイル: routes.py プロジェクト: Siequnu/flask-classes
def create_lesson_api ():
    if app.models.is_admin (current_user.username):
        try:
            lesson_objects = request.json['lessonObjects']
            for lesson_object in lesson_objects:

                lesson = Lesson(
                    start_time = lesson_object['startTime'],
                    end_time = lesson_object['endTime'],
                    date = lesson_object['date'],
                    turma_id = lesson_object['turmaId']
                )
                db.session.add(lesson)
                db.session.commit()

            flash ('All lessons added successfully', 'success')
            return jsonify ({'success': 'All lessons added successfully.'})

        except:
            flash ('An error occured while adding the lessons', 'error')
            return jsonify ({'error': 'An error occured while adding the lessons.'})
    abort (403)
コード例 #19
0
def createLesson():
    form = LessonForm()
    if form.validate_on_submit():
        try:
            user = current_user
            if stopFileUpload(request, 'Image'):
                return render_template('createLesson.html', title='Create Lesson', form=form)
            imgFilename = saveFileReturnFileName(request, 'Image')
            if stopFileUpload(request, 'Video'):
                return render_template('createLesson.html', title='Create Lesson', form=form)
            vidFilename = saveFileReturnFileName(request, 'Video')
            lesson = Lesson(name=form.name.data, description=form.description.data, 
                            duration=form.duration.data, imgFileLoc=imgFilename,
                            vidFileLoc=vidFilename, createdBy=user.id )
            db.session.add(lesson)
            db.session.commit()
            flash('Nice, you have created a lesson')
            return redirect(url_for('editLesson', lessonId=lesson.id))
        except IntegrityError: 
            db.session.rollback()
            flash('This title is already in use.  Please try another.')
            return redirect(url_for('createLesson'))
    return render_template('createLesson.html', title='Create Lesson', form=form)
コード例 #20
0
ファイル: views.py プロジェクト: kurlova/Flask-Photo-Service
def create_course():
    course_data = request.get_json()
    c_name = course_data["data"]["c_name"]
    c_description = course_data["data"]["c_description"]
    c_img = course_data["data"]["c_image"]
    creator_id = course_data["data"]["creator_id"]
    cost = course_data["data"]["cost"]
    course_format = course_data["data"]["course_format"]
    course = Course(name=c_name,
                    description=c_description,
                    img=c_img,
                    creator_id=creator_id,
                    cost=cost,
                    course_format=course_format)
    db.session.add(course)
    db.session.commit()
    lessons = course_data["data"]["lessons"]
    for les in range(len(lessons)):
        les_name = lessons[les]["les_name"]
        les_description = lessons[les]["les_description"]
        les_number = lessons[les]["les_number"]
        lesson = Lesson(course_id=course.id,
                        name=les_name,
                        description=les_description,
                        number=les_number)
        db.session.add(lesson)
        db.session.commit()
        for vid in range(len(lessons[les]["videos"])):
            video_name = lessons[les]["videos"][vid]["vid_name"]
            video_link = lessons[les]["videos"][vid]["link"]
            video = Video(lesson_id=lesson.id,
                          name=video_name,
                          link=video_link)
            db.session.add(video)
            db.session.commit()
    return jsonify({'status': 'ok'}), 200
コード例 #21
0
    def test_class(self):
        with self.app.app_context():
            u0 = User(username='******',
                      email='*****@*****.**',
                      first_name='zack',
                      last_name='zhu')
            c0 = Class(title='swimming class')
            c1 = Class(title='soccer class')
            u0.created_classes.append(c0)
            u0.created_classes.append(c1)
            db.session.add(u0)
            db.session.commit()
            assert c0.creator == u0

            cs0 = ClassSession(class_id=c0.id, creator_id=u0.id)

            ts0 = TimeSlot(start_at=datetime(2018, 2, 27, 11, 59, 59),
                           duration=30)
            ts1 = TimeSlot(start_at=datetime(2018, 2, 28, 11, 59, 59),
                           duration=60)
            end_at = datetime(2018, 3, 14, 9, 59, 59)
            sch0 = Schedule(repeat_option=RepeatOption.WEEKLY,
                            repeat_end_at=end_at,
                            base_time_slots=[ts0, ts1])
            cs0.schedule = sch0
            self.db.session.add(cs0)
            self.db.session.commit()

            tl0 = TemplateLesson(class_session_id=cs0.id, time_slot=ts0)
            tl1 = TemplateLesson(class_session_id=cs0.id, time_slot=ts1)
            cs0.template_lessons = [tl0, tl1]
            lessons = cs0.create_lessons()
            # db.session.add_all(lessons)
            # db.session.commit()
            l0 = Lesson(class_session=cs0)
            print(l0.type)

            # [cs0.lessons.append(l) for l in lessons]
            # cs0.lessons.append(l0)
            cs0.lessons = lessons + [l0]
            self.db.session.add(cs0)
            self.db.session.commit()
            print(cs0.template_lessons[:])
            print(cs0.lessons[0].type)
            exit()

            cs1 = ClassSession(class_id=c1.id, creator_id=u0.id)
            ts2 = TimeSlot(start_at=datetime(2018, 12, 27, 11, 59, 59),
                           duration=30)
            ts3 = TimeSlot(start_at=datetime(2018, 12, 28, 11, 59, 59),
                           duration=60)
            end_at = datetime(2019, 1, 20, 9, 59, 59)
            sch1 = Schedule(repeat_option=RepeatOption.WEEKLY,
                            repeat_end_at=end_at,
                            base_time_slots=[ts2, ts3])
            cs1.schedule = sch1
            tl2 = TemplateLesson(class_session_id=cs1.id, time_slot=ts2)
            tl3 = TemplateLesson(class_session_id=cs1.id, time_slot=ts3)
            cs1.template_lessons = [tl2, tl3]
            lessons = cs1.create_lessons()
            self.db.session.add(cs1)
            self.db.session.commit()
            print(cs1.template_lessons[:])
            print(cs1.lessons[:])

            print(self.db.session.query(Lesson).all())
コード例 #22
0
def savelesson(studentId, uid, year, term):
    #这也是一个内部方法,用来在课程页查询这个学生的课程信息,并且保存在数据库里面
    studentName = getname(uid=uid)
    try:
        tempstudentobj = Student.objects.get(studentID=studentId)
    except:
        # 放学生用户
        tempstudentobj = Student(studentID=studentId, name=studentName)
        tempstudentobj.save()

    link = requests.session()
    link.cookies.set('JSESSIONID', uid)
    oriurl = r'http://jwk.lzu.edu.cn/academic/student/currcourse/currcourse.jsdo?'
    url = oriurl + 'year=' + year + '&' + 'term=' + term
    lessonHTML = link.get(url)
    temp = lessonHTML.text
    bs = BeautifulSoup(temp)
    temp = bs.find(name='table', class_='infolist_tab')
    temp2 = temp.find_all(name='tr', class_='infolist_common')
    allresult = temp2
    out = {}
    number1 = []
    number2 = []
    lesson = []
    teacher = []
    for i in allresult:
        number1.append(i.find_all(name='td')[0].text.strip())
        number2.append(i.find_all(name='td')[1].text.strip())
        lesson.append(i.find_all(name='td')[2].text.strip())
        teacher.append(i.find_all(name='td')[3].text.strip())

    # for i in range(0, len(allresult), 2):
    #     if i + 1 >= len(allresult):
    #         break
    #     out[allresult[i].string.strip()] = allresult[(i + 1)].string.strip()
    # for i, j in out.items():
    #     lesson.append(i)
    #     teacher.append(j)
    #
    # temp = bs.find_all(name="tr", class_="infolist_common")
    # for i in range(0, len(teacher)):
    #     number1.append(temp[i].find_next(name="td").string.strip())
    #     number2.append(temp[i].find_next(name="td").find_next(name="td").string.strip())
    tempteacherid = []
    # 先放老师
    for te in teacher:
        try:
            temp = Teacher.objects.get(name=te)
        except:
            temp = Teacher(name=te)
            temp.save()
        tempteacherid.append(temp.id)
    # 放课程
    templessonobj = []
    for i in range(0, len(lesson)):
        try:
            temp = Lesson.objects.get(lessonNumA=number1[i], lessonNumB=number2[i])
        except:
            temp = Lesson(lessonName=lesson[i], lessonNumA=number1[i], lessonNumB=number2[i],
                          teacherObj=Teacher.objects.get(pk=tempteacherid[i]), lessonCredit=2)
            temp.save()
        templessonobj.append(temp)

    # 中间表把学生和课程联系起来
    for i in templessonobj:
        try:
            LessonComment.objects.get(studentObj=tempstudentobj, lessonObj=i)
        except:
            temp = LessonComment(studentObj=tempstudentobj, lessonObj=i)
            temp.save()
コード例 #23
0
ファイル: test_lesson_model.py プロジェクト: amanya/backdne
    def test_get_finished_lessons(self):
        ls = [
            Lesson(lesson="lesson1", user_id=1, is_finished=False),
            Lesson(lesson="lesson1", user_id=1, is_finished=False),
            Lesson(lesson="lesson2", user_id=1, is_finished=False),
            Lesson(lesson="lesson2", user_id=1, is_finished=True),
            Lesson(lesson="lesson3", user_id=1, is_finished=True),
            Lesson(lesson="lesson3", user_id=1, is_finished=True),
            Lesson(lesson="lesson1", user_id=2, is_finished=True),
            Lesson(lesson="lesson1", user_id=2, is_finished=True),
            Lesson(lesson="lesson4", user_id=2, is_finished=False),
            Lesson(lesson="lesson4", user_id=2, is_finished=False)
        ]

        for l in ls:
            db.session.add(l)

        db.session.commit()

        finished_lessons = Lesson.get_finished_lessons(1)

        expected = {
            "lesson1": False,
            "lesson2": True,
            "lesson3": True,
        }

        self.assertEqual(finished_lessons, expected)
コード例 #24
0
ファイル: lesson_service.py プロジェクト: jesusking52/myriver
def create_lesson(user_id):
    if user_id is None:
        raise InvalidTokenError()
    user = User.query.get(user_id)
    if user.type != UserType.STUDENT:
        raise InvalidArgumentError(
            extra_message='It can be available only by student.')
    lesson = Lesson.query \
        .filter((Lesson.status == LessonStatus.BIDDING) | (Lesson.status == LessonStatus.DEALING)) \
        .filter(Lesson.owner_id == user_id).first()
    if lesson is not None:
        raise ElementAlreadyExists(extra_message='Student already has lesson.')
    student = user.student
    lesson = Lesson()
    lesson.owner_id = user.id
    lesson.status = LessonStatus.BIDDING
    current_time = current_millis()
    lesson.created_at = current_time
    lesson.created_time = datetime.utcnow()

    lesson.email = user.email
    lesson.name = user.name
    lesson.gender = user.gender
    lesson.phone_number = user.phone_number
    lesson.birth_year = user.birth_year
    lesson.zip_code = user.zip_code
    lesson.address = user.address
    lesson.sido = user.sido
    lesson.sigungu = user.sigungu
    lesson.bname = user.bname
    lesson.latitude = user.latitude
    lesson.longitude = user.longitude
    lesson.student_status = student.student_status
    lesson.grade = student.grade
    lesson.department = student.department
    lesson.level = student.level
    lesson.class_available_count = student.class_available_count
    lesson.class_time = student.class_time
    lesson.class_type = student.class_type
    lesson.preferred_gender = student.preferred_gender
    lesson.preferred_price = student.preferred_price
    lesson.description = student.description
    lesson.available_subjects = []
    for subject in student.available_subjects:
        lesson.available_subjects.append(subject)
    lesson.available_days_of_week = []
    for day_of_week in student.available_days_of_week:
        lesson.available_days_of_week.append(day_of_week)
    db.session.add(lesson)
    db.session.commit()
    add_notification(NotificationRequest().to(user_id).on_start_bidding(
        lesson.id))
    return lesson
コード例 #25
0
ファイル: views.py プロジェクト: qwert2603/crmit
def lessons_in_month(group_id, month_number):
    group = Group.query.get_or_404(group_id)
    if month_number < group.start_month or month_number > group.end_month:
        abort(404)
    month_name = get_month_name(month_number)
    students_in_group = group.students_in_group_in_month(month_number) \
        .join(Student, Student.id == StudentInGroup.student_id) \
        .order_by(Student.fio) \
        .all()
    if 'submit' in request.form:
        if not can_user_write_group(current_user, group): abort(403)
        ls = Lesson.lessons_in_group_in_month(group_id, month_number).all()
        ps = Payment.query \
            .join(StudentInGroup, StudentInGroup.id == Payment.student_in_group_id) \
            .filter(StudentInGroup.group_id == group_id, Payment.month == month_number)
        payments = dict()
        for p in ps:
            payments[p.student_in_group_id] = p
        for student_in_group in students_in_group:
            new_value = request.form.get('p_{}'.format(student_in_group.id),
                                         0,
                                         type=int)
            if new_value < 0: new_value = 0
            max_value = group.section.price - student_in_group.discount
            if new_value > max_value: new_value = max_value
            payment = payments.get(student_in_group.id)
            is_cash = 'c_{}'.format(student_in_group.id) in request.form
            comment = request.form.get(
                'comment_{}'.format(student_in_group.id), '')
            if payment is not None:
                if not payment.confirmed:
                    payment.value = new_value
                    payment.cash = is_cash
                    payment.comment = comment
            else:
                db.session.add(
                    Payment(student_in_group=student_in_group,
                            month=month_number,
                            value=new_value,
                            cash=is_cash,
                            comment=comment))
            attendings = dict()
            for l in ls:
                attendings[l.id] = dict()
                for a in l.attendings:
                    attendings[l.id][a.student_id] = a
            for l in ls:
                attending = attendings[l.id].get(student_in_group.student_id)
                a_key = 'a_{}_{}'.format(l.id, student_in_group.student_id)
                new_state = request.form.get(a_key,
                                             attending_was_not,
                                             type=int)
                if attending is not None:
                    attending.state = new_state
                else:
                    db.session.add(
                        Attending(lesson=l,
                                  student=student_in_group.student,
                                  state=new_state))
        flash('посещения и оплата в группе {} за {} сохранены.'.format(
            group.name, month_name))
        return redirect(
            url_for('lessons.lessons_in_month',
                    group_id=group_id,
                    month_number=month_number))
    pd = payments_in_month_info(group_id, month_number)
    ll = lessons_lists(group_id, month_number)
    return render_template('lessons/lessons_in_month.html',
                           group=group,
                           month_number=month_number,
                           month_name=month_name,
                           students_in_group=students_in_group,
                           payments=pd.values,
                           confirmed=pd.confirmed,
                           cash=pd.cash,
                           comments=pd.comments,
                           lessons=ll[0],
                           attendings_states=ll[1],
                           write_mode=can_user_write_group(
                               current_user, group))
コード例 #26
0
ファイル: db_populate.py プロジェクト: sredmond/apc
with open('app/static/json/references.json') as f:
    references = json.loads(f.read())

# Seconds since epoch at which a new PST day w/ physics begins
epoch_day_offsets = [timegm(time.strptime(date, "%m/%d/%y")) for date in dates]

# Used to iterate through our potential times
time_iter = iter(epoch_day_offsets)

# Populate the lessons into their respective units, including dates
for unit in content:
    unit_model = Unit()
    unit_model.title = unit.get('title')
    unit_model.description = unit.get('description')
    for lesson in unit['lessons']:
        lesson_model = Lesson()
        for item in lesson['items']:
            lesson_model.addItem(item)
        lesson_model.homework=lesson.get('homework')
        lesson_model.additional = lesson.get('additional')

        # Add time values
        t = time_iter.next() # Seconds since epoch of a new UTC day - could throw an error
        pst_dt = datetime.utcfromtimestamp(t) # Datetime representing the local date and time
        lesson_model.epoch_time = t + pst_offset # Seconds since epoch of a new PST day
        lesson_model.pst_datetime = pst_dt
        lesson_model.day_of_week = int(pst_dt.strftime("%w")) # 1 = Monday, 2 = Tuesday, ..., 5 = Friday
        lesson_model.week_of_year = int(pst_dt.strftime("%W"))

        unit_model.addLesson(lesson_model)
    unit_model.visible = True
コード例 #27
0
ファイル: manage.py プロジェクト: cash2one/Y-System
def deploy():
    '''
    Run deployment tasks.
    '''

    # migrate database to latest revision
    from flask_migrate import upgrade
    upgrade()

    # insert data
    from app.models import Color
    Color.insert_entries()

    from app.models import Permission
    Permission.insert_entries()

    from app.models import Role
    Role.insert_entries()

    from app.models import IDType
    IDType.insert_entries()

    from app.models import Gender
    Gender.insert_entries()

    from app.models import Relationship
    Relationship.insert_entries()

    from app.models import PurposeType
    PurposeType.insert_entries()

    from app.models import ReferrerType
    ReferrerType.insert_entries()

    from app.models import BookingState
    BookingState.insert_entries()

    from app.models import AssignmentScoreGrade
    AssignmentScoreGrade.insert_entries()

    from app.models import GREAWScore
    GREAWScore.insert_entries()

    from app.models import ScoreLabel
    ScoreLabel.insert_entries()

    from app.models import InvitationType
    InvitationType.insert_entries()

    from app.models import EducationType
    EducationType.insert_entries()

    from app.models import ScoreType
    ScoreType.insert_entries()

    from app.models import CourseType
    CourseType.insert_entries()

    from app.models import iPadCapacity
    iPadCapacity.insert_entries()

    from app.models import iPadState
    iPadState.insert_entries()

    from app.models import Room
    Room.insert_entries()

    from app.models import Lesson
    Lesson.insert_entries()

    from app.models import Section
    Section.insert_entries()

    from app.models import Assignment
    Assignment.insert_entries()

    from app.models import Test
    Test.insert_entries()

    from app.models import AnnouncementType
    AnnouncementType.insert_entries()

    from config import basedir
    data = raw_input(u'Enter data identifier (e.g.: initial or 20160422): ')
    datadir = os.path.join(basedir, 'data', data)
    if os.path.exists(datadir):
        from app.models import User
        User.insert_entries(data=data, basedir=basedir)

        from app.models import UserCreation
        UserCreation.insert_entries(data=data, basedir=basedir)

        from app.models import Punch
        Punch.insert_entries(data=data, basedir=basedir)

        from app.models import Tag
        Tag.insert_entries(data='initial', basedir=basedir)

        from app.models import Product
        Product.insert_entries(data='initial', basedir=basedir)

        from app.models import Course
        Course.insert_entries(data='initial', basedir=basedir)

        from app.models import Period
        Period.insert_entries(data='initial', basedir=basedir)

        from app.models import iPad
        iPad.insert_entries(data='initial', basedir=basedir)

        from app.models import iPadContent
        iPadContent.insert_entries(data='initial', basedir=basedir)

        from app.models import NotaBene
        NotaBene.insert_entries(data='initial', basedir=basedir)

        from app.models import Feed
        Feed.insert_entries(data=data, basedir=basedir)
    else:
        print u'---> Invalid data identifier: %s' % data
コード例 #28
0
ファイル: lessons.py プロジェクト: oro13/totlahtol_backend
def get_lessons():
    page = request.args.get('page', 1, type=int)
    per_page = min(request.args.get('per_page', 10, type=int), 100)
    data = Lesson.to_collection_dict(Lesson.query, page, per_page, 'api.get_lessons')
    return jsonify(data)