def one_blog_page(id): form = CommentsForm() db_sess = db_session.create_session() if form.validate_on_submit(): comment = Comments() comment.text = form.content.data comment.news_id = int(id) comment.name_id = current_user.id db_sess.add(comment) db_sess.commit() return redirect(f'/blogs/{id}') news = db_sess.query(News).filter(News.id == id) comms = db_sess.query(Comments).filter(Comments.news_id == id) comments = [] for c in comms: user = db_sess.query(User).filter(User.id == c.name_id).first() comments.append((user.name, c.text)) cmnts = False if comms is None else True return render_template('one_blog_page.html', news=news[0], current_user=current_user, comms=comms, cmnts=cmnts, form=form, comments=comments)
def post(current_user, self, post_id, comment_id=None): if not isinstance(post_id, str) or len(post_id) != 24: abort(400, message="{} is not a valid post id".format(post_id)) if comment_id is not None: abort(405, message="Can't POST to this endpoint. Try /post/<post id>/comment") post_data = Posts.objects(id=post_id).first() if post_data is None: abort(404, message="Post with id '{}' doesn't exist".format(post_id)) received_json = request.get_json() errors = validate_values_in_dictionary( received_json, Comments, required_keys={'body'}) if errors: abort(400, errors=errors) try: new_comment = Comments( author=current_user, body=received_json['body'], rating=Ratings() ) post_data.comments.append(new_comment) post_data.save() current_user.comments.append(new_comment) # TODO fix saving comments to user # current_user.save() except Exception as e: abort(400, errors=str(e)) return {'message': "Comment posted successfully", 'comment': new_comment.to_json()}, 201
def add_comment(id): form = CommentsForm() db_sess = db_session.create_session() post = db_sess.query(Posts).filter(Posts.id == id).first() # Если комментарий пэтаются оставить под чужим приватным постом или его пытается оставить пользователь # с ролью "Наблюдатель" - ошибка 404 if post and (not post.is_private or ( post.is_private and post.user == current_user)) and current_user.role != "Spectator": if form.validate_on_submit(): comment = Comments() # Содержание комментария - не более 200 символов if len(form.text.data) > 200: return render_template('Comment.html', title='Adding a comment', form=form, post=post, message="This comment is too big, please, enter up to 200 characters") comment.text = form.text.data comment.post_id = id # Добавляем комментарий к пользователю и к посту current_user.comments.append(comment) db_sess.merge(current_user) db_sess.merge(db_sess.query(Posts).filter(Posts.id == id).first()) db_sess.commit() # Пересылаем пользователя на страницу поста, под которым он оставил комментарий return redirect(f'/post/{id}') return render_template('Comment.html', title='Adding a comment', form=form, post=post) else: abort(404)
def comm_add(new_id): """ Обработка добавления комментария :param new_id: id новости в DB, к которой добавляется комментарий :return: форма для добавления комментария """ form = ComForm() if form.validate_on_submit(): db_sess = db_session.create_session() to_new = db_sess.query(News).filter(News.id == new_id).first() idd = len(db_sess.query(Comments).all()) + 1 if len(to_new.comms) > 0: to_new.comms = str(to_new.comms) + ';{}'.format(idd) else: to_new.comms = idd com = Comments() com.user_id = current_user.id com.content = form.content.data com.created_date = datetime.datetime.now() db_sess.add(com) db_sess.add(to_new) db_sess.commit() return redirect('/') return render_template("add_com.html", form=form, title='Добавить комментарий')
def news(id): db_sess = create_session() ns = db_sess.query(News).filter(News.id == id).first() if not ns: return not_found_news() if ns.is_private and ns.user_id != current_user.id: return abort(405) form = CommentsForm() if form.validate_on_submit(): comment = Comments(comment=form.comment.data, news_id=ns.id, user_id=current_user.id, is_private=form.is_private.data, news=ns) db_sess.add(comment) comment.post() db_sess.commit() return redirect(f'/news/{id}') comments = ns.get_comments(privat=current_user == ns.user) return render_template('news/news.html', title=ns.title, item=ns, comments=comments, form=form, liked=any( filter(lambda x: x.user == current_user, ns.likes)))
def comment_db(rating, n_of_order, comment): com = Comments() com.rate = rating com.number_of_order = n_of_order com.comment = comment db_sess = db_session.create_session() db_sess.add(com) db_sess.commit()
def news_item(id): db_sess = db_session.create_session() if current_user.is_authenticated: form = CommentForm() if form.validate_on_submit(): comm = Comments() comm.connected_to_id = id comm.table_name = News.__tablename__ comm.author_id = current_user.id comm.text = form.text.data comm.date = datetime.datetime.now() comm.likes_count = 0 db_sess.add(comm) db_sess.commit() else: form = None data = db_sess.query(News).get(id) comments = db_sess.query(Comments).filter( Comments.connected_to_id == id, Comments.table_name == News.__tablename__) return render_template("news_item.html", news=data, title=data.title, comments=comments, form=form)
def add_comment(id): form = CommentForm() if form.validate_on_submit(): session = db_session.create_session() comment = Comments() comment.text = form.text.data comment.news_id = id current_user.comments.append(comment) session.merge(current_user) session.commit() return redirect('/') return render_template('comments.html', title='Добавление комментария', form=form)
def add_com(): form = ComForm() if form.validate_on_submit(): session = db_session.create_session() com = Comments() com.title = form.title.data com.content = form.content.data current_user.com.append(com) session.merge(current_user) session.commit() return redirect('/download') return render_template('addCom.html', title='Добавление комментария', form=form)
def index(category_id: int = 0): form = CommentForm() db_sess = db_session.create_session() if category_id != 0: news = db_sess.query(News).filter( News.category_id == category_id).order_by( News.created_date.desc()).all() else: news = db_sess.query(News).order_by(News.created_date.desc()).all() categories = db_sess.query(Category).all() if not category_id: title = "Последние новости" else: title, = [i.name for i in categories if i.id == category_id] if form.validate_on_submit(): comment = Comments(content=form.content.data, users_id=current_user.id, news_id=int(form.news_id.data)) db_sess.add(comment) db_sess.commit() return redirect(f"/{category_id}") return render_template("index.html", news=news, form=form, category=categories, title=title)
def inf_ask(qst_id): form = CommForm() db_sess = db_session.create_session() ask = db_sess.query(Questions).filter(Questions.id == qst_id).first() if not ask: return render_template('error404.html') user = db_sess.query(User).filter(User.id == ask.author).first() param = return_files(form=form, ava=user.photo) ask.popular += 1 db_sess.commit() if form.validate_on_submit(): text = form.comment.data comment = Comments(question_id=qst_id, comment=text, author=current_user.id) db_sess.add(comment) db_sess.commit() param['stay_photo'] = 1 if ask.photo in ('fon.png', '0_fon.png'): param['stay_photo'] = 0 else: param['fon_li'] = url_for('static', filename=f'img/avatars/{ask.photo}') comment = db_sess.query(Comments).filter(Comments.question_id == qst_id) comments = [] for i in comment: user = db_sess.query(User).filter(User.id == i.author).first() comments.append([i.id, i.color, i.comment, user.name, user.surname, url_for('static', filename='img/avatars/' + user.photo), i.date, 'pers_account/' + str(i.author)]) return render_template('read_ask.html', **param, ask=ask, commentar=comments)
def add_comment(): db_sess = db_session.create_session() comment = Comments( question_id=1, comment='Не знаю, нужно покапаться в инете', ) db_sess.add(comment) db_sess.commit()
def publication(id): status = 0 if current_user.is_authenticated: status = current_user.status + 1 session = db_session.create_session() publication = session.query(Publications).get(id) session.close() if publication: form = CommentsForm() if form.submit.data: if current_user.is_authenticated: session = db_session.create_session() user = session.query(User).get(current_user.id) publication = session.query(Publications).get(id) comment = Comments() comment.text = form.text.data comment.created_date = datetime.datetime.now() form.text.data = "" user.comments.append(comment) session.merge(user) publication.comments.append(comment) session.merge(publication) session.commit() session = db_session.create_session() comments = session.query(Comments).filter(Comments.publication_id == id).order_by( Comments.created_date.desc()).all() templ = render_template("/Publication.html", publication=publication, status=status, user=current_user, style=url_for('static', filename='css/style.css'), form=form, comments=comments, count_commentaries=len(comments), base_href=f"Publication/{id}/", bgimg=get_image_profile(current_user)) session.close() return templ else: comments = session.query(Comments).filter(Comments.publication_id == id).order_by( Comments.created_date.desc()).all() templ = render_template("/Publication.html", publication=publication, status=status, user=current_user, style=url_for('static', filename='css/style.css'), form=form, comments=comments, count_commentaries=len(comments), base_href=f"Publication/{id}/", bgimg=get_image_profile(current_user)) session.close() return templ session.close() return redirect('/Publications')
def developers_diary(id): status = 0 if current_user.is_authenticated: status = current_user.status + 1 session = db_session.create_session() ds_diary = session.query(DevelopersDiary).filter(DevelopersDiary.id == id).first() session.close() ds_diary.created_date = ":".join(str(ds_diary.created_date).split(":")[:-1]) if status >= ds_diary.availability_status: form = CommentsForm() if form.submit.data: if current_user.is_authenticated: session = db_session.create_session() user = session.query(User).get(current_user.id) diary = session.query(DevelopersDiary).get(id) comment = Comments() comment.text = form.text.data comment.created_date = datetime.datetime.now() form.text.data = "" user.comments.append(comment) session.merge(user) diary.comments.append(comment) session.merge(diary) session.commit() session = db_session.create_session() comments = session.query(Comments).filter(Comments.developers_diary_publication_id == id).order_by( Comments.created_date.desc()).all() templ = render_template("/DevelopersDiary.html", publication=ds_diary, status=status, user=current_user, style=url_for('static', filename='css/style.css'), form=form, comments=comments, count_commentaries=len(comments), base_href=f"DevelopersDiaryPublication/{id}/", bgimg=get_image_profile(current_user)) session.close() return templ else: comments = session.query(Comments).filter(Comments.developers_diary_publication_id == id).order_by( Comments.created_date.desc()).all() templ = render_template("/DevelopersDiary.html", publication=ds_diary, status=status, user=current_user, style=url_for('static', filename='css/style.css'), form=form, comments=comments, count_commentaries=len(comments), base_href=f"DevelopersDiaryPublication/{id}/", bgimg=get_image_profile(current_user)) session.close() return templ return redirect('/DevelopersDiary')
def index(): session = db_session.create_session() # Отображение новостей if current_user.is_authenticated: news = session.query(News).filter((News.user == current_user) | (News.is_private != True)) else: news = session.query(News).filter(News.is_private != True) # Отображение комментариев comments = session.query(Comments).filter() # Форма для добавления комментария form = CommentForm() if form.validate_on_submit(): comment = Comments() comment.text = form.text.data comment.news_id = int(''.join(form.news_id.raw_data)) current_user.comment.append(comment) session.merge(current_user) session.commit() return redirect('/') # Форма для удаления комментария delete_form = CommentDelete() if delete_form.validate_on_submit() and current_user.is_authenticated: comm = session.query(Comments).filter(Comments.id == int(''.join( delete_form.comment_id.raw_data))).first() if comm: session.delete(comm) session.commit() else: abort(404) return redirect('/') return render_template("index.html", news=news, comments=comments, form=form, form_del=delete_form, title="Форум Питонистов")
def post(self): """Добавление комментария""" parser = reqparse.RequestParser() parser.add_argument('post_id', required=True, type=int) parser.add_argument('content', required=True) parser.add_argument('author', required=True, type=int) args = parser.parse_args() session = db_session.create_session() comm = Comments( post_id=args['post_id'], content=args['content'], author=args['author'] ) session.add(comm) session.commit() return jsonify({'success': 'OK'})
def music_page(name_music, name_author, id, user_id): session = db_session.create_session() # Забираем все нужные данные data_music = session.query(Content).filter(Content.user_id == user_id, Content.id == id).first() # Добавляем комментарий пользователя в бд form = CommentsForm() if form.validate_on_submit(): text = Comments(text=form.comment.data, content_id=id, user_name=flask_user.current_user.name) session.add(text) session.commit() # Снова открываем эту же страницу для отображения нового комментария return redirect( '/' + '/'.join(['music', name_music, name_author, id, user_id])) comments = session.query(Comments).filter(Comments.content_id == id).all() return render_template('music_page.html', title_music=name_music, title_author=name_author, data=data_music, form=form, comments=reversed(comments))
def comment(id): form = CommentForm() session = db_session.create_session() news = session.query(News).filter(News.id == id).first() if form.validate_on_submit(): comments = Comments() comments.content = form.content.data f = form.photo.data if f: filename = secure_filename(f.filename) f.save(os.path.join(app.static_folder, 'img', filename)) comments.photo = f.filename comments.news_id = id comments.user_id = current_user.name session.add(comments) session.commit() return redirect('/') return render_template('comments.html', form=form, news=news)
if item and item.quantity_in_stock > 0: item.quantity_in_stock = item.quantity_in_stock - 1 session.commit() return render_template("buy_item.html", have=True, item=item, bgimg=get_image_profile(current_user), style=url_for('static', filename='css/style.css')) else: session.close() return render_template("buy_item.html", have=False, item=item, bgimg=get_image_profile(current_user), style=url_for('static', filename='css/style.css')) if __name__ == '__main__': # create_products() main(port=8000) create_new_db = False if create_new_db: db_session.global_init("Followers_Rjkzavrs.sqlite") session = db_session.create_session() user = User() session.add(user) session.commit() session = db_session.create_session() session.add(Publications()) session.add(DevelopersDiary()) session.add(Products()) session.commit() session = db_session.create_session() session.add(Comments()) session.commit() print('Успех!')