Beispiel #1
0
    def get_day_language_xp_list(self,
                                 since: arrow.Arrow) -> List[DailyLanguageXp]:
        cache_key = get_key_with_prefix(
            f"{self.username}_{since.strftime('%Y-%m-%d')}", 'day_language_xp')
        lock_key = get_key_with_prefix(cache_key, 'lock')

        data = cache.get(cache_key)
        # add lock to make sure only one request is fetching response from server (hopefully)
        lock = cache.cache.inc(lock_key, delta=1)
        set_redis_expire_seconds(lock_key, 15)
        while data is None and isinstance(lock, int) and lock > 1:
            time.sleep(1)
            data = cache.get(cache_key)
            lock = cache.get(lock_key)

        if data is None:
            post_data = '''{
                profile(username: "******") {
                    day_language_xps: dayLanguageXps(since: "%s") {date language xp}
                }
            }''' % (self.username, since.strftime('%Y-%m-%d'))
            response_json = requests.post(
                'https://codestats.net/profile-graph', data=post_data).json()
            current_app.logger.info('response json from %s: %s', self.username,
                                    response_json)
            data = response_json['data']['profile']['day_language_xps']
            cache.set(cache_key, data, timeout=30 * 60)
            current_app.logger.info('set cache [%s]', cache_key)
        cache.delete(lock_key)

        self.day_language_xp_list = DailyLanguageXpSchema().load(data,
                                                                 many=True)
        return self.day_language_xp_list
def delete_lesson(lesson_id):
    lesson = Lesson.query.get_or_404(lesson_id)

    cache.delete(cache_key_for_students_marks(lesson.group_id, lesson.discipline_id))

    lesson.delete()
    return Response()
def delete_lesson(lesson_id):
    lesson = Lesson.query.get_or_404(lesson_id)

    cache.delete(
        cache_key_for_students_marks(lesson.group_id, lesson.discipline_id))

    lesson.delete()
    return Response()
def create_lesson():
    form = LessonCreateForm(request.form)
    if form.validate_on_submit():
        lesson = Lesson()
        populate(form, lesson)
        lesson.save()

        cache.delete(cache_key_for_students_marks(lesson.group_id, lesson.discipline_id))
        return Response()

    return Response(pformat(form.errors), status=400)
def update_lesson(lesson_id):
    lesson = Lesson.query.get_or_404(lesson_id)

    form = LessonEditForm(request.form, lesson)
    if form.validate_on_submit():
        populate(form, lesson)
        lesson.update()
        cache.delete(cache_key_for_students_marks(lesson.group_id, lesson.discipline_id))
        return Response()

    return Response(status=400)
def create_lesson():
    form = LessonCreateForm(request.form)
    if form.validate_on_submit():
        lesson = Lesson()
        populate(form, lesson)
        lesson.save()

        cache.delete(
            cache_key_for_students_marks(lesson.group_id,
                                         lesson.discipline_id))
        return Response()

    return Response(pformat(form.errors), status=400)
def update_lesson(lesson_id):
    lesson = Lesson.query.get_or_404(lesson_id)

    form = LessonEditForm(request.form, lesson)
    if form.validate_on_submit():
        populate(form, lesson)
        lesson.update()
        cache.delete(
            cache_key_for_students_marks(lesson.group_id,
                                         lesson.discipline_id))
        return Response()

    return Response(status=400)
    def post(self):
        marks = request.get_json()
        for mark in marks:
            m = Mark.query.filter(Mark.student_id == mark["student_id"], Mark.lesson_id == mark["lesson_id"]).first()
            if m is None:
                m = Mark(student_id=mark["student_id"], lesson_id=mark["lesson_id"])
                db.session.add(m)
            m.value = mark["value"]

        # reset cache
        for lesson in Lesson.query.filter(Lesson.id.in_([m["lesson_id"] for m in marks])).all():
            cache.delete(cache_key_for_students_marks(lesson.group_id, lesson.discipline_id))

        db.session.commit()

        return Response()
    def post(self):
        marks = request.get_json()
        for mark in marks:
            m = Mark.query.filter(Mark.student_id == mark['student_id'],
                                  Mark.lesson_id == mark['lesson_id']).first()
            if m is None:
                m = Mark(student_id=mark['student_id'],
                         lesson_id=mark['lesson_id'])
                db.session.add(m)
            m.value = mark['value']

        # reset cache
        for lesson in Lesson.query.filter(
                Lesson.id.in_([m['lesson_id'] for m in marks])).all():
            cache.delete(
                cache_key_for_students_marks(lesson.group_id,
                                             lesson.discipline_id))

        db.session.commit()

        return Response()
Beispiel #10
0
def reset_student_marks_cache_for_discipline_id(discipline_id):
    for (group_id,) in Group.query.with_entities(Group.id).all():
        cache.delete(cache_key_for_students_marks(group_id, discipline_id))
Beispiel #11
0
    def post(self, obj_id='', operation=''):

        form = self.form()
        cache.delete('index')
        cache.delete('detail')

        if obj_id:

            obj = self.model.query.get(obj_id)

            for attr, value in obj.__dict__.items():
                if attr not in [
                        '_sa_instance_state', 'id', 'created_on', 'updated_on',
                        'rate_average', 'total'
                ]:
                    setattr(obj, attr, form[attr].data)

            if hasattr(form, 'images'):
                if form.images.data:
                    uploaded_files = request.files.getlist(form.images.name)
                    for file in uploaded_files:
                        # Check if the file is one of the allowed types/extensions
                        if file and allowed_file(file.filename):
                            # Make the filename safe, remove unsupported chars
                            filename = secure_filename(file.filename)
                            filename = gen_file_name(filename)
                            mime_type = file.content_type
                            # Move the file form the temporal folder to the upload
                            # folder we setup
                            file.save(
                                os.path.join(app.config['UPLOAD_FOLDER'],
                                             filename))
                            # path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                            upload_obj = self.rel_mode(filename=filename)
                            obj.images.append(upload_obj)
                            if mime_type.startswith('image'):
                                create_thumbnail(filename)

            else:
                if form.filename.data:
                    file = request.files[form.filename.name]
                    if file and allowed_file(file.filename):
                        filename = secure_filename(file.filename)
                        filename = gen_file_name(filename)
                        mime_type = file.content_type
                        file.save(
                            os.path.join(app.config['UPLOAD_FOLDER'],
                                         filename))
                        form.filename.data = filename

                        if mime_type.startswith('image'):
                            create_thumbnail(filename)
                    form.populate_obj(obj)

        else:
            obj = self.model()
            if hasattr(form, 'images'):
                form = self.form()

                for attr, value in obj.__dict__.items():
                    if attr not in '_sa_instance_state':
                        setattr(obj, attr, form[attr].data)
                if form.images.data:
                    uploaded_files = request.files.getlist(form.images.name)
                    for file in uploaded_files:
                        # Check if the file is one of the allowed types/extensions
                        if file and allowed_file(file.filename):
                            # Make the filename safe, remove unsupported chars
                            filename = secure_filename(file.filename)
                            filename = gen_file_name(filename)
                            # Move the file form the temporal folder to the upload
                            # folder we setup
                            file.save(
                                os.path.join(app.config['UPLOAD_FOLDER'],
                                             filename))
                            upload_obj = self.rel_mode(filename=filename)
                            obj.images.append(upload_obj)
                    try:
                        db.session.add(obj)
                        db.session.commit()
                    except IntegrityError as e:
                        app.logger.error(e)
                        db.session.rollback()
                return redirect(self.path)

            elif hasattr(form, 'filename'):
                if form.filename.data:
                    file = request.files[form.filename.name]
                    if file and allowed_file(file.filename):
                        filename = secure_filename(file.filename)
                        filename = gen_file_name(filename)
                        mime_type = file.content_type
                        file.save(
                            os.path.join(app.config['UPLOAD_FOLDER'],
                                         filename))
                        form.filename.data = filename

                        if mime_type.startswith('image'):
                            create_thumbnail(filename)
                    try:
                        form.populate_obj(obj)
                        db.session.add(obj)
                        db.session.commit()
                    except IntegrityError as e:
                        app.logger.error(e)
                        db.session.rollback()

                flash("Achievement created")

                return redirect(self.path)

            elif hasattr(form, 'dates_available'):
                obj = self.rel_mode()
                obj2 = self.model(dates_available=form.dates_available.data)
                obj.dates.append(obj2)
                db.session.add(obj)
            else:
                form.populate_obj(obj)
                db.session.add(obj)

        # form.populate_obj(obj)
        db.session.commit()
        return redirect(self.path)
Beispiel #12
0
    def get(self, obj_id='', operation=''):
        cache.delete('index')
        cache.delete('detail')

        obj = self.model.query.get(obj_id)

        if operation == 'delete':

            if hasattr(obj, 'filename'):
                path = os.path.join(app.config['UPLOAD_FOLDER'], obj.filename)
                file_thumb_path = os.path.join(app.config['THUMBNAIL_FOLDER'],
                                               obj.filename)
                if os.path.exists(path):
                    try:
                        os.remove(path)
                        if os.path.exists(file_thumb_path):
                            os.remove(file_thumb_path)
                        db.session.delete(obj)
                        db.session.commit()
                    except OSError as e:
                        print("Error: %s - %s." % (e.obj.filename, e.strerror))
                else:
                    print("Sorry, I can not find %s file." % obj.filename)
                    db.session.delete(obj)
                    db.session.commit()

            elif hasattr(obj, 'images'):
                for img_name in obj.images.all():
                    path = os.path.join(app.config['UPLOAD_FOLDER'],
                                        img_name.filename)
                    file_thumb_path = os.path.join(
                        app.config['THUMBNAIL_FOLDER'], img_name.filename)
                    if img_name.filename:
                        if os.path.exists(path):
                            try:
                                os.remove(path)
                                if os.path.exists(file_thumb_path):
                                    os.remove(file_thumb_path)
                                db.session.delete(obj)
                                db.session.commit()
                            except OSError as e:
                                print("Error: %s - %s." %
                                      (e.img_name.filename, e.strerror))
                        else:
                            print("Sorry, I can not find %s file." %
                                  img_name.filename)
                            db.session.delete(obj)
                            db.session.commit()
            else:
                db.session.delete(obj)
                db.session.commit()
            return redirect(self.path)

        elif operation == 'delete_image':
            obj = self.rel_mode.query.get(obj_id)
            path = os.path.join(app.config['UPLOAD_FOLDER'], obj.filename)
            file_thumb_path = os.path.join(app.config['THUMBNAIL_FOLDER'],
                                           obj.filename)
            if os.path.exists(path):
                try:
                    os.remove(path)
                    if os.path.exists(file_thumb_path):
                        os.remove(file_thumb_path)
                    db.session.delete(obj)
                    db.session.commit()
                except OSError as e:
                    print("Error: %s - %s." % (e.obj.filename, e.strerror))
            else:
                print("Sorry, I can not find %s file." % obj.filename)
                db.session.delete(obj)
                db.session.commit()

            return redirect(request.environ['HTTP_REFERER'])

        elif operation == 'new':
            form = self.form()
            action = self.path
            return self.render_detail(form=form, action=action)

        elif operation == 'edit':
            obj = self.model.query.get(obj_id)
            # populate the form with our blog data
            form = self.form(obj=obj)
            # action is the url that we will later use
            # to do post, the same url with obj_id in this case
            action = request.path
            return self.render_detail(form=form, action=action, obj=obj)

        else:
            page_num = int(request.args.get('page', 1))
            col = self.model.__table__.columns.keys()
            col_names = [name for name in col if name not in self.exclude]
            obj = self.model.query.order_by(
                self.model.created_on.desc()).paginate(page=page_num,
                                                       per_page=5,
                                                       error_out=True)
            endpoint = self.endpoint
            return self.render_list(obj=obj,
                                    col_names=col_names,
                                    endpoint=endpoint)
Beispiel #13
0
def reset_student_marks_cache_for_discipline_id(discipline_id):
    for (group_id, ) in Group.query.with_entities(Group.id).all():
        cache.delete(cache_key_for_students_marks(group_id, discipline_id))