示例#1
0
    def post(self):
        args = parser.parse_args()
        session = db_session.create_session()

        film = Film(title=args['title'],
                    rating=args['rating'],
                    actors=args['actors'],
                    producer=args['producer'],
                    duration=args['duration'],
                    description=args['description'],
                    poster_url=args['poster_url'],
                    trailer_url=args['trailer_url'],
                    watchers=args['watchers'])
        print(args['genres'])
        if args['premiere']:
            film.premiere = datetime.fromisoformat(args['premiere'])
        genres = list(map(lambda x: x.lower(), args['genres']))
        for genre_name in genres:
            genre = session.query(Genre).filter(
                Genre.name == genre_name).first()
            if genre is None:
                genre = Genre()
                genre.name = genre_name
            film.genre.append(genre)
        for image_url in args['images']:
            image = session.query(Image).filter(
                Image.image_url == image_url).first()
            if image is None:
                image = Image()
                image.image_url = image_url
            film.images.append(image)
        session.add(film)
        session.commit()
        return jsonify({'success': 'OK'})
示例#2
0
def users_main():
    db_sess = db_session.create_session()
    users = db_sess.query(User).all()
    tmp = [user.image for user in db_sess.query(User).all()]
    images = []
    for image_id in tmp:
        try:
            images.append(
                db_sess.query(Image).filter(Image.id == image_id).first().path)
        except Exception:
            images.append(None)
    lst = []
    if current_user.is_authenticated:
        for elem in db_sess.query(Page).filter(Page.author == current_user.id):
            lst.append(elem)
        image = db_sess.query(Image).filter(
            Image.id == current_user.image).first()
        if not image:
            image = Image()
            image.path = '/static/profile_images/standart_user.png'
            db_sess.add(image)
            current_user.image = image.id
            db_sess.commit()
        if current_user.type != 'admin':
            pages = [
                elem for elem in lst
                if elem.type == 'page_of_book' and elem.edit_type == 'edited'
            ]
            articles = [
                elem for elem in lst
                if elem.type == 'article' and elem.edit_type == 'edited'
            ]
            history = [
                elem for elem in lst
                if elem.type == 'story' and elem.edit_type == 'edited'
            ]
        else:
            pages = [elem for elem in lst if elem.type == 'page_of_book']
            articles = [elem for elem in lst if elem.type == 'article']
            history = [elem for elem in lst if elem.type == 'story']
        return render_template('users.html',
                               title='Пользователи',
                               pages=pages,
                               articles=articles,
                               history=history,
                               profile_image=image.path,
                               users=users,
                               user_images=images)
    else:
        return render_template('users.html',
                               title='Пользователи',
                               users=users,
                               user_images=images)
示例#3
0
def edit_news(params):
    news_id = int(params.split('$')[0])
    part_num = int(params.split('$')[1])
    db_sess = db_session.create_session()
    news = db_sess.query(News).filter(News.id == news_id).first()
    main_form = NewsCreatePageForm()
    part_form = NewsPartForm()
    with open(news.json_page, encoding="utf8") as file:
        page_json = json.load(file)
    if main_form.is_submitted():
        news.header = main_form.header.data
        news.about = main_form.about.data
        try:
            page_json['content'][part_num][
                'header'] = part_form.part_header.data
            page_json['content'][part_num]['content'] = part_form.content.data
            if part_form.load_image.data:
                image_data = part_form.load_image.data
                db_image = Image()
                db_sess.add(db_image)
                db_sess.commit()
                filename = secure_filename(image_data.filename)
                db_image.path = os.path.join('static/news_images/image' +
                                             str(db_image.id) + '.jpg')
                image_data.save(db_image.path)
                page_json['content'][part_num]['imgs'].append(db_image.id)
            db_sess.commit()
        except Exception:
            pass
        with open(news.json_page, 'w', encoding="utf8") as file:
            json.dump(page_json, file, ensure_ascii=False, indent=2)
        db_sess.commit()
        return redirect('/edit_news/{}'.format(params))
    main_form.header.data = news.header
    main_form.about.data = news.about
    if news.author != current_user.id:
        return redirect('/users')
    try:
        part_form.part_header.data = page_json['content'][part_num]['header']
        part_form.content.data = page_json['content'][part_num]['content']
        part_form.img_lst = [
            db_sess.query(Image).filter(Image.id == elem).first().path
            for elem in page_json['content'][part_num]['imgs']
        ]
    except:
        pass
    return render_template('edit_news.html',
                           title='Редактирование новости',
                           news=news,
                           main_form=main_form,
                           part_form=part_form,
                           json=page_json)
示例#4
0
def create_thread_page():
    form = ThreadCreateForm()
    if form.validate_on_submit():
        thread_title = form.title.data
        thread_theme = form.theme.data
        thread_main_text = form.text.data
        # Создаем запись в таблице posts
        post = Post()
        post.type = 'thread'
        post.created_date = datetime.now().date()
        post.created_time = datetime.now().time()
        db_sess = db_session.create_session()
        db_sess.add(post)
        db_sess.commit()
        # Собираем фотографии с формы
        images = []
        for file in [
                form.image_1.data, form.image_2.data, form.image_3.data,
                form.image_4.data
        ]:
            if file:
                filename = secure_filename(file.filename)
                filename = generate_s(9) + '.' + filename.split('.')[-1]
                filepath = 'static/images/' + filename
                file.save(filepath)
                image = Image()
                image.post_id = post.id
                image.title = filename
                image.file_path = filepath
                images.append(filepath)
                db_sess.add(image)
                db_sess.commit()
        # Создаем запись в таблице threads
        thread = Thread()
        thread.title = form_text(thread_title, 156)
        thread.post_id = post.id
        thread.theme = form_text(thread_theme, 156)
        thread.main_text = form_text(thread_main_text, 156)
        thread.images = images
        thread.answers_amount = 0
        thread.date = post.created_date.strftime("%d/%m/%Y")
        thread.time = post.created_time.strftime("%H.%M.%S")
        db_sess.add(thread)
        db_sess.commit()
        return redirect('/home')
    param = dict()
    param['title'] = 'Три.ч - Создание треда'
    param['form'] = form
    return render_template('create-thread.html', **param)
示例#5
0
def add_building():
    form = BuildingForm()
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        if len(form.tags.data) >= 29 * 3:
            line_tags = form.tags.data[:29 * 3 - 3] + '...'
        else:
            line_tags = form.tags.data + ' ' * (29 * 3 - len(form.tags.data))
        item = Item(name=form.name.data,
                    about=form.about.data,
                    tags=line_tags,
                    price=form.price.data,
                    address=form.address.data,
                    image_link=form.image_link.data.split()[0])
        current_user.items.append(item)
        db_sess.merge(current_user)
        db_sess.commit()
        for items in form.image_link.data.split():
            image = Image(estate_id=db_sess.query(Item).filter(
                Item.name == item.name).first().id,
                          link=items)
            db_sess.add(image)
        db_sess.commit()
        return redirect('/catalog')
    return render_template('building_info_edit.html',
                           title='Добавление здания',
                           form=form)
示例#6
0
def reqister():
    form = RegisterForm()
    if form.validate_on_submit():
        if form.password.data != form.password_again.data:
            return render_template('register.html',
                                   title='Регистрация',
                                   form=form,
                                   message="Пароли не совпадают!")
        db_sess = db_session.create_session()
        if db_sess.query(User).filter(User.email == form.email.data).first():
            return render_template('register.html',
                                   title='Регистрация',
                                   form=form,
                                   message="Такой пользователь уже есть")
        image = Image()
        user = User(name=form.name.data,
                    email=form.email.data,
                    about=form.about.data,
                    image=30,
                    type='user')
        user.set_password(form.password.data)
        db_sess.add(user)
        db_sess.commit()
        return redirect('/login')
    return render_template('register.html',
                           title='Регистрация',
                           form=form,
                           message='')
示例#7
0
def edit_user(user_id):
    if current_user.id != user_id:
        return redirect('/users')
    db_sess = db_session.create_session()
    user = db_sess.query(User).filter(User.id == user_id).first()
    form = ProfileEditForm()
    if form.validate_on_submit():
        if user.check_password(form.old_password.data):
            if form.new_password.data:
                user.name = form.login.data
                user.about = form.about.data
                user.email = form.email.data
                if form.load_image.data:
                    image_data = form.load_image.data
                    db_image = Image()
                    db_sess.add(db_image)
                    db_sess.commit()
                    filename = secure_filename(image_data.filename)
                    db_image.path = os.path.join(
                        'static/profile_images/image' + str(db_image.id) +
                        '.jpg')
                    image_data.save(db_image.path)
                    user.image = db_image.id
                    db_sess.commit()
                user.set_password(form.new_password.data)
                db_sess.commit()
                return redirect('/users')
            else:
                return render_template(
                    'edit_user.html',
                    form=form,
                    message='Новый пароль не может быть пустым!',
                    title='Изменение профиля')
        else:
            return render_template('edit_user.html',
                                   form=form,
                                   message='Старый пароль введен неверно!',
                                   title='Изменение профиля')
    form.login.data = user.name
    form.about.data = user.about
    form.email.data = user.email
    return render_template('edit_user.html', form=form)
示例#8
0
def edit_building(id):
    form = BuildingForm()
    db_sess = db_session.create_session()
    arr = []
    for i in db_sess.query(Image).filter(Image.estate_id == id).all():
        arr.append(i.link)
    images_h = ' '.join(arr)
    if request.method == "GET":
        db_sess = db_session.create_session()
        items = db_sess.query(Item).filter(Item.id == id,
                                           Item.user == current_user).first()
        print(items)
        if items:
            form.name.data = items.name
            form.about.data = items.about
            form.tags.data = items.tags
            form.price.data = items.price
            form.address.data = items.address
            form.image_link.data = images_h
            print(items)
        else:
            abort(404)
    if form.validate_on_submit():
        db_sess = db_session.create_session()
        items = db_sess.query(Item).filter(Item.id == id,
                                           Item.user == current_user).first()
        print(len(form.tags.data))
        if len(form.tags.data) >= 29 * 3:
            line_tags = form.tags.data[:29 * 3 - 3] + '...'
        else:
            line_tags = form.tags.data + ' ' * (29 * 3 - len(form.tags.data))
        if items:
            items.name = form.name.data
            items.about = form.about.data
            items.tags = line_tags
            items.price = form.price.data
            items.address = form.address.data
            items.image_link = form.image_link.data.split()[0]
            for item in form.image_link.data.split():
                if item not in images_h:
                    image = Image(estate_id=id, link=item)
                    db_sess.add(image)
            db_sess.commit()
            return redirect('/post_edit')
        else:
            abort(404)

    return render_template('building_info_edit.html',
                           title='Редактирование информации о здании',
                           form=form)
示例#9
0
def user_info(user_id):
    db_sess = db_session.create_session()
    user = db_sess.query(User).filter(User.id == user_id).first()
    user_image = db_sess.query(Image).filter(Image.id == user.image).first()
    if not user_image:
        image = Image()
        image.path = '/static/profile_images/standart_user.png'
        db_sess.add(image)
        db_sess.commit()
        user.image = image.id
        user_image = image
    lst = []
    for elem in db_sess.query(Page).filter(Page.author == user.id):
        lst.append(elem)
    pages = [elem for elem in lst if elem.type == 'page_of_book']
    articles = [elem for elem in lst if elem.type == 'article']
    history = [elem for elem in lst if elem.type == 'story']
    return render_template('user_info.html',
                           title='Информация о пользователе',
                           user=user,
                           profile_image=user_image.path,
                           pages=pages,
                           articles=articles,
                           history=history)
示例#10
0
def answer_page(post_id):
    db_sess = db_session.create_session()
    answering_to = post_id
    response = db_sess.query(Post).filter(Post.id == answering_to)
    type_of_post = None
    for p in response:
        type_of_post = p.type
    form = AnswerForm()
    if form.validate_on_submit():
        answer_text = form.text.data
        # Заводим запись в таблице posts
        post = Post()
        post.type = 'answer'
        post.created_date = datetime.now().date()
        post.created_time = datetime.now().time()
        db_sess.add(post)
        db_sess.commit()
        # Бежим по фотографиям
        images = []
        for file in [
                form.image_1.data, form.image_2.data, form.image_3.data,
                form.image_4.data
        ]:
            if file:
                filename = secure_filename(file.filename)
                filename = generate_s(9) + '.' + filename.split('.')[-1]
                filepath = 'static/images/' + filename
                file.save(filepath)
                image = Image()
                image.post_id = post.id
                image.title = filename
                image.file_path = filepath
                images.append(filepath)
                db_sess.add(image)
                db_sess.commit()
        # Создаем запись об ответе
        answer = Answer()
        answer.main_text = form_text(answer_text, 176)
        answer.post_id = post.id
        answer.answering_to = answering_to
        answer.images = images
        answer.date = post.created_date.strftime("%d/%m/%Y")
        answer.time = post.created_time.strftime("%H.%M.%S")
        answer.thread_id = answering_to
        if type_of_post == 'thread':
            answer.thread_id = answering_to
            db_sess.add(answer)
            db_sess.commit()
            return redirect(f'/thread/{answering_to}')
        else:
            post = None
            for a in db_sess.query(Answer).filter(
                    Answer.post_id == answering_to):
                post = a
            answer.thread_id = post.thread_id
            db_sess.add(answer)
            db_sess.commit()
            return redirect(f'/thread/{post.thread_id}')
    param = dict()
    param['title'] = f'Три.ч - Ответ №{answering_to}'
    param['post_type'] = type_of_post
    if type_of_post == 'thread':
        param['posts'] = db_sess.query(Thread).filter(
            Thread.post_id == answering_to)
    else:
        param['posts'] = db_sess.query(Answer).filter(
            Answer.post_id == answering_to)
    param['form'] = form
    return render_template('answer.html', **param)
示例#11
0
def edit_page(page_info):
    print(page_info)
    db_sess = db_session.create_session()
    main_form = CreatePageForm()
    part_form = PartForm()
    page_id = int(page_info.split('$')[1])
    page_type = page_info.split('$')[0]
    part_num = int(page_info.split('$')[2])
    page = db_sess.query(Page).filter(Page.id == page_id).first()
    print('user_type =', current_user.type)
    if current_user.type != 'admin':
        if page.author != current_user.id:
            return redirect('/users')
    with open(page.json_page, encoding="utf8") as file:
        page_json = json.load(file)
    if main_form.is_submitted():
        page.header = main_form.header.data
        page.about = main_form.about.data
        try:
            page_json['content'][part_num][
                'header'] = part_form.part_header.data
            page_json['content'][part_num]['content'] = part_form.content.data
            if part_form.load_image.data:
                image_data = part_form.load_image.data
                db_image = Image()
                db_sess.add(db_image)
                db_sess.commit()
                filename = secure_filename(image_data.filename)
                if page_type == 'article':
                    db_image.path = os.path.join(
                        'static/article_images/image' + str(db_image.id) +
                        '.jpg')
                elif page_type == 'story':
                    db_image.path = os.path.join(
                        'static/history_images/image' + str(db_image.id) +
                        '.jpg')
                else:
                    db_image.path = os.path.join('static/book_images/image' +
                                                 str(db_image.id) + '.jpg')
                image_data.save(db_image.path)
                page_json['content'][part_num]['imgs'].append(db_image.id)
            db_sess.commit()
        except Exception:
            pass
        with open(page.json_page, 'w', encoding="utf8") as file:
            json.dump(page_json, file, ensure_ascii=False, indent=2)
        db_sess.commit()
        return redirect('/edit_page/{}'.format(page_info))
    main_form.header.data = page.header
    main_form.about.data = page.about
    try:
        part_form.part_header.data = page_json['content'][part_num]['header']
        part_form.content.data = page_json['content'][part_num]['content']
        part_form.img_lst = [
            db_sess.query(Image).filter(Image.id == elem).first().path
            for elem in page_json['content'][part_num]['imgs']
        ]
    except:
        pass
    title = 'страницы книги'
    if page_type == 'article':
        title = 'статьи'
    if page_type == 'story':
        title = 'истории'
    return render_template('edit_page.html',
                           title='Редактирование {}'.format(title),
                           page=page,
                           main_form=main_form,
                           part_form=part_form,
                           json=page_json)