def submit_comment_poopstream(): comment = request.json['comment'] commenter_id = request.json['session_id'] comment_time = datetime.utcnow() comment_message = request.json['message'] if comment != '': if commenter_id == '': commenter_id = 'Anonymous' new_comment = Comments(comment=comment, commenter_name=commenter_id, comment_time=comment_time, comment_message=comment_message) db.session.add(new_comment) db.session.commit() return jsonify(success=True) else: find_user_name = Users_v2.query.filter_by( id=commenter_id).first().username new_comment = Comments(comment=comment, commenter_name=find_user_name, comment_time=comment_time, comment_message=comment_message) db.session.add(new_comment) db.session.commit() return jsonify(success=True) return jsonify(success=False)
def create_comment(user): try: body = dict(request.form) print(body) if (body["comment"] is None): return jsonify({"msg": "debes escribir un comentario"}), 400 # img if (len(request.files) > 0): f = request.files['attached'] #filename= secure_filename(f.filename)Al usar cloudinary no lo necesito #f.save(os.path.join("./img",filename))Al usar cloudinary no lo necesito img_url = save_image(f) if user['rol'] != 'Profesional': new_comment = Comments(text=body['comment'], attached=img_url, id_traveler=user['id'], id_pro=None, id_offer=body["id_offer"]) else: new_comment = Comments(text=body['comment'], attached=img_url, id_traveler=None, id_pro=user['id'], id_offer=body["id_offer"]) else: #not image if user['rol'] != 'Profesional': new_comment = Comments(text=body['comment'], id_traveler=user['id'], id_pro=None, id_offer=body["id_offer"]) else: new_comment = Comments(text=body['comment'], id_traveler=None, id_pro=user['id'], id_offer=body["id_offer"]) db.session.add(new_comment) db.session.commit() return jsonify(new_comment.serialize()), 200 except OSError as error: print('error', error) return jsonify("Error"), 400 except Exception as err: print(err) return jsonify("Error"), 500
def alojamiento(request, ident): if request.user.is_authenticated(): logged = True try: usersel = UserSels.objects.get(user=request.user.username, alojamiento_id=ident) except UserSels.DoesNotExist: usersel = UserSels(user=request.user.username, date=datetime.datetime.now(), alojamiento_id=ident) usersel.save() else: logged = False if request.method == 'POST': alojamiento = Alojamientos.objects.get(id=int(ident)) comment = Comments(text=request.POST['comment'], date=datetime.datetime.now(), alojamiento_id=int(ident)) comment.save() try: alojamiento = Alojamientos.objects.get(id=ident) except Alojamientos.DoesNotExist: return HttpResponse( "El alojamiento al que intentas acceder no esta disponible") images = Images.objects.filter(alojamiento_id=ident) template = get_template('alojamiento.html') context = ({ 'home': request.get_host(), 'username': request.user.username, 'logged': logged, 'alojamiento': alojamiento, 'images': images }) return HttpResponse(template.render(context))
def add_comment(): comment = request.form.get('comment') life_id = request.form.get('life_id') '''算法开始''' index_now = compute_model(comment) print(str(index_now)) life = Life.query.filter(Life.id == life_id).first() author = User.query.filter(User.id == life.author_id).first() character = Characters.query.filter( Characters.user_id == author.id).first() if character.rank: string = float(character.rank) string += index_now character.rank = str(string) db.session.commit() else: character.rank = str(index_now) db.session.commit() '''算法结束''' comments = Comments(content=comment) comments.life_id = life_id user_id = session.get('user_id') comments.user_id = user_id db.session.add(comments) db.session.commit() return redirect(url_for('details', life_id=life_id))
def post(self, post_id): renderComment = RenderComment() render = RenderPost() login = self.read_cookie('login') uid = None if login: uid = int(login) user = Users.get_by_id(uid) content = self.request.get("content") post = Post.get_by_id(int(post_id)) likes = post.likes.count() comments = post.comments.order("-date") if uid: if content: comment = Comments(post=post, user=user, content=content) comment.put() self.redirect("/blog/" + post_id) else: self.render("permalink.html", post=post, error="", likes=likes, render=render, comment_error="Type something!", renderComment=renderComment, comments=comments) else: self.render("permalink.html", post=post, error="", likes=likes, render=render, comment_error="you must be logged in", renderComment=renderComment, comments=comments)
def post(self, task_id): if task_id is None: return {'message': 'Bad task id, you must be admin'}, 401 user = User.current() if user is None: # or user.role != 'admin': return {'message': 'Bad user, you must be admin'}, 401 data = request.get_json() if data is not None: if 'message' in data: c = Comments(task_id=task_id, inspector_id=user.id, message=data['message']) db.session.add(c) else: tsk = Tasks.query.filter_by(task_id=task_id).first() if tsk is None: return {'message': 'Bad task, you must be admin'}, 401 inspect = json.loads(tsk.inspect) if tsk.inspect else {} if 'rating' in data: inspect['rating'] = data['rating'] if 'progress' in data: inspect['progress'] = data['progress'] if 'status' in data: inspect['status'] = data['status'] tsk.inspect = json.dumps(inspect) db.session.add(tsk) db.session.commit() return {'message': 'Task was updated successful'}
def curd_comments(): req = json.loads(json.dumps(request.get_json())) if request.method == "GET" and admin_check(current_user.id): t_list = [] for data in Comments.query.all(): t_list.append(data.as_dict()) return jsonify(t_list) elif not "cards_id" in req: return ("400: Bad Request") if (int(req["cards_id"]) in mem_access( current_user.id)["cards"]) or (admin_check(current_user.id)): if request.method == "POST": comments = Comments() comments.content = req["content"] comments.cards_id = req["cards_id"] comments.user_id = req["user_id"] db.session.add(comments) if request.method == "PUT": comments = Comments.query.filter_by(id=req["id"]).first() comments.content = req["content"] comments.cards_id = req["cards_id"] comments.user_id = req["user_id"] if request.method == "DELETE": Comments.query.filter_by(id=req["id"]).delete() db.session.commit() return ("Request Processed")
def read_blog(id): user = checkUser() blogs = Blogs.query.filter_by(id = id).all() if len(blogs) == 0: blog = '' else: blog = blogs[0] commentResult = Comments.query.filter_by(blog_id= id).order_by(Comments.created_at.desc()).all() comments = [] for c in commentResult: like = Likes.query.filter(and_(Likes.user_id.like(user.id),Likes.comment_id.like(c.id))).all() if len(like): c.canLike = True else: c.canLike = False comments.append(c) blog.htmlcontent = markdown2.markdown(blog.content) form = CommentForm() if request.method == 'GET': return render_template( "blog.html", blog = blog, user = user, comments = comments, base64=base64, form = form, ) if request.method == 'POST': content = form.comment.data comment = Comments(id = str(uuid1()),blog_id = blog.id,blog_name = blog.name,user_id = user.id,user_name = user.name,user_image = user.image,content = content) db.session.add(comment) db.session.commit() return redirect('/blog/'+blog.id)
def add_comment_api(): if 'username' not in session: return "Must be authenticated", Status.HTTP_BAD_FORBIDDEN current_user = session['username'] image_id = request.form['image_id'] comment = request.form['comment'] if not image_id or not comment: return "Missing required parameter", Status.HTTP_BAD_REQUEST if not Image.query.filter(Image.id == image_id).first(): return "Invalid image id", Status.HTTP_BAD_REQUEST if not Image.query.filter(Image.id == image_id).first( ).owner == session['username'] and not Viewable.query.filter( Viewable.image_id == image_id and Viewable.user_name == current_user).first(): return "You do not have permissions for this image", Status.HTTP_BAD_UNAUTHORIZED # Now can comment db.session.add( Comments(parent_image=image_id, author=current_user, comment_string=comment)) db.session.commit() return "Successfully added comment", Status.HTTP_OK_BASIC
def iepginput(d): a_title = Title(name=d['program-title']) b_waves = Waves(name=d['station']) c_station = Station(name=d['station-name']) d_comments = Comments(name=d['comment']) op = timeset(d, start) ed = timeset(d, end) sg1 = d['genre-1'] * 16 + d['subgenre-1'] if d['genre-2'] == 0: x = Program(title=a_title, program_id=d['program-id'], waves=b_waves, station=c_station, start=op, end=ed, gen_1=d['genre-1'], sgn_1=sg1, comments=d_comments) x.save else: sg2 = d['genre-2'] * 16 + d['subgenre-2'] x = Program(title=a_title, program_id=d['program-id'], waves=b_waves, station=c_station, start=op, end=ed, gen_1=d['genre-1'], sgn_1=sg1, gen_2=d['genre-2'], sgn_2=sg2, comments=d_comments) x.save
def index(): from models import Articles, Comments from forms import ArticlesForm, CommentsForm if request.method == 'POST': print(request.form) us_form = ArticlesForm(request.form) if us_form.validate(): post_art = Articles(**us_form.data) db.session.add(post_art) db.session.commit() return 'Article was created' else: us_form = CommentsForm(request.form) if us_form.validate(): post_com = Comments(**us_form.data) db.session.add(post_com) db.session.commit() return 'Commit was created' else: raise Exception if request.method == 'GET': vie_posts = Articles.query.all() return render_template('home.txt', posts=vie_posts)
def post(self): user = self.user username = str(self.user.auth_ids) username = username.split('\'') message = self.request.get('message') newComment = self.request.get('newComment') if (message): newPost = Post(msg=message, userid=user.key) newPost.put() self.redirect("/wall") else: uid = self.request.get('uid') if (newComment): postMural = ndb.Key(urlsafe=uid).get() postMural.comments.append( Comments(msg=newComment, user_name_lastname=user.name + " " + user.last_name, user_auth_ids=username[1])) postMural.put() self.redirect("/wall") else: if (uid): postMural = ndb.Key(urlsafe=uid).get() params = {} params['params'] = postMural params['user'] = user self.render('wall.html', params)
def get_single_comment(id): with sqlite3.connect("./rare.db") as conn: conn.row_factory = sqlite3.Row db_cursor = conn.cursor() # Use a ? parameter to inject a variable's value # into the SQL statement. db_cursor.execute(""" SELECT c.id, c.post_id, c.author_id, c.content, c.created_on FROM comments as c WHERE c.id = ? """, ( id, )) # Load the single result into memory data = db_cursor.fetchone() # Create an comment instance from the current row comment = Comments(data['id'], data['post_id'], data['author_id'], data['content'], data['created_on']) return json.dumps(comment.__dict__)
def save_to_database(self): self._parse() for i in range(len(self.id)): try: comment = Comments( id=int(self.id[i]), username=self.username[i], user_center=self.user_center[i], vote=int(self.vote[i]), star=self.star[i], time=datetime.strptime(self.time[i], '%Y-%m-%d %H:%M:%S'), content=self.content[i] ) self.session.add(comment) self.session.commit() return 'finish' except pymysql.err.IntegrityError as e: print('数据重复,不做任何处理') except Exception as e: #数据添加错误,回滚 self.session.rollback() finally: #关闭数据库连接 self.session.close()
def change_comment(n): form = AddComments() form.date.data = dt.date.today() if request.method == "GET": db_sess = Session() comments = db_sess.query(Comments).filter(Comments.id == n).first() db_sess.close() form.title.data = comments.title form.text.data = comments.text form.date.data = comments.date if form.validate_on_submit(): comments = Comments() comments.id = n comments.title = form.title.data text = form.text.data comments.text = text.replace('\n', '|') comments.date = form.date.data comments.user_id = current_user.get_id() db.session.merge(comments) db.session.commit() flash('Comment has been added') return redirect('/comments') return render_template('add_comments.html', form=form)
def add_comment(obj_type=None, obj_id=None, user=None, comment=None): if not obj_type: obj_type = request.form.get('obj_type') if not obj_id: obj_id = request.form.get('obj_id') if not user: user = request.form.get('user', current_user.id) if not comment: comment = request.form.get('comment') if obj_type and obj_id and user and comment and obj_type in ( 'report', 'requirement', 'req', 'indicator'): new_comment = Comments(user=user) new_comment.comment = comment if obj_type == 'report': new_comment.report = obj_id elif obj_type == 'requirement' or obj_type == 'req': new_comment.requirement = obj_id else: new_comment.indicator = obj_id add_db_entry(new_comment) return ('success') return ('Comment insert failed.')
def add_comment(request, user, image): owner = True if image.owner != user.username: owner = False image_route = "https://screenshot-tool-eecs498.herokuapp.com/api/get-image?id=" + str( image.id) new_comment = request.form['comment'] db.session.add( Comments(parent_image=image.id, author=user.username, comment_string=new_comment)) db.session.commit() comments = Comments.query.filter( Comments.parent_image == image.id).order_by(Comments.timestamp) options = { 'user': user, 'image': image, 'comments': comments, 'owner': owner, 'image_route': image_route, 'add_viewer_message': "" } return render_template('details.html', **options), Status.HTTP_OK_BASIC
def submitcomment(request, name): #get form data user = request.POST['user'] comment = request.POST['comment'] prof = Professors.objects.get(name = name) #get professor we are talking about comm = Comments(professor=prof,user=user,comment=comment) #create Comment entry comm.save() #insert into database return redirect('/data/' + name) #display the new data on the professor's page
def create_comment(user): body = request.get_json() print(body) new_comment = Comments(text=body['text'], user_id=user['user']['id'], recipe_id=body['recipe_id']) print(new_comment) db.session.add(new_comment) db.session.commit() return jsonify(new_comment.serialize()), 201
def post(self): song_id = self.get_argument("song_id") song_id = int(song_id) user_id = self.get_argument("user_id") user_id = int(user_id) msg = self.get_argument("msg") comment = Comments(content=msg, author_id=user_id, song_id=song_id) self.session.add(comment) self.session.commit() self.write(dict(ret=0))
def create_comment(ref_type, ref_id, content): content = _RE_COMMENT.sub('', content) if len(content) > 1000: raise APIValueError('content', 'exceeded maximun length: 1000.') u = ctx.user return Comments(user_id=u._id, user_name=u.name, user_image_url=u.image_url, ref_id=ref_id, ref_type=ref_type, content=content).insert()
def create_comment(): author = login() message = input('Enter your comment: ') while not re.match("^[a-zA-Z0-9 ]{5,}$", message): print('Please enter a valid comment.') message = input('Enter your comment: ') else: comment = Comments(message, author) Store.comments.append(comment.__dict__) print('comment successfully created')
def add_comment(current_user): data = request.json public_id=str(uuid.uuid4()) new_comment= Comments( public_id=public_id, text=data['text'], post_id=data['post_id'], user_id=current_user.public_id ) db.session.add(new_comment) db.session.commit() return jsonify({'msg':'Comment Posted.','id':public_id})
def show_post(index): form = CommentForm() requested_post = BlogPost.query.get(index) if form.validate_on_submit(): new_text = Comments(body=form.body.data, user_id=current_user.id, post_id=requested_post.id) db.session.add(new_text) db.session.commit() return redirect(url_for('show_post', index=requested_post.id)) return render_template("post.html", post=requested_post, logged_in=current_user.is_authenticated, form=form)
def post(self, module_id, campain_id): text = self.request.get("comment") user = users.get_current_user() comment = Comments(text=text.strip(), userMail=user.email(), userId=user.user_id(), campanya=campain_id, module=module_id) comment.put() time.sleep(0.1) return webapp2.redirect("/foro/" + str(module_id) + "/" + str(campain_id))
def comment(): new_comment = request.form.get('comment') question_id = request.form.get('question_id') answer = Comments(comment_content=new_comment) user_id = session.get('user_id') user = User.query.filter(User.id == user_id).first() answer.author = user question = Question.query.filter(Question.id == question_id).first() answer.question = question db.session.add(answer) db.session.commit() return redirect(url_for('detail', question_id=question_id))
def submit_comment(): comment = request.json['comment'] commenter_name = request.json['name'] comment_time = datetime.utcnow() comment_message = request.json['message'] if comment != '': if commenter_name == '': commenter_name = 'Anonymous' new_comment = Comments(comment=comment, commenter_name=commenter_name, comment_time=comment_time, comment_message=comment_message) db.session.add(new_comment) db.session.commit() return jsonify(success=True)
def add_comment(): """ Send a commentary to one beach""" req = request.get_json(force=True) beach_id = req["beach_id"] comment = req["comment"] user_id = flask_praetorian.current_user_id() try: db.session.add( Comments(comment=comment, user_id=user_id, beach_id=beach_id)) db.session.commit() except Exception as e: return {"Error": str(e)}, 500 comment_id = db.session.query(Comments.id).filter_by( user_id=user_id, beach_id=beach_id).first() return {"message": f"comment with id {comment_id} post correctly"}, 200
def home(request): blog_posts = load_blog() results = [] archieves = [] for blog in blog_posts: body = blog.body new_list = [m.start() for m in re.finditer(r"<br />", body)] new_line = body.index('<br />') for item in new_list: if item >= 750: new_line = item break body = body[:new_line] pre_start_list = [m.start() for m in re.finditer(r"<pre ", body)] pre_end_list = [m.start() for m in re.finditer(r"</pre>", body)] if pre_start_list: if not pre_end_list: pre_end = [ m.start() for m in re.finditer(r"</pre>", blog.body) ][0] body = blog.body[:pre_end] archieves.append(blog.title) date = blog.day[:10] day = date[8:10] month = date[5:7] mnth = get_month(month) results.append({ 'day': day, 'month': mnth, 'body': body, 'title': blog.title }) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): data = form.cleaned_data p = Comments(name=data['name'], comment=data['comment'], title=request.POST['post_title']) p.save() comments = Comments.objects.order_by("-id") return render( request, 'home.html', { 'posts': results, 'outline': archieves, 'comments': comments, 'form': CommentForm })
def blog_post(blog_post_title): whole_blog_post = db_session.query(Blog_Post).filter(Blog_Post.title == blog_post_title).first() blog_post_comments = db_session.query(Blog_Post).options(lazyload('comments')).all() if request.method == 'POST': user_name = request.form['user_name'] content = request.form['content'] new_comment = Comments(user_name, content, whole_blog_post) db_session.add(new_comment) try: print("sucsess") db_session.commit() except exc.SQLAlchemyError: print "error" pass return redirect(url_for('routes.blog_post',blog_post_title=whole_blog_post.title)) return render_template('blogpost.html', blog_post = whole_blog_post, comments = blog_post_comments)