def create_post(): post_data = request.get_json(force=True, silent=True) if post_data == None: return "Bad request", 400 post = Post(get_id(), post_data["title"], post_data["content"]) POSTS[post.id] = post return json.dumps(post.to_dict()), 201
def new_post(self): title = input("Enter post title:") content = input("Enter post:") date = input("Enter date or leave for today(ddmmyyyy):") post = Post(self.author,title,content,self.id,datetime.datetime.strptime(date,"%d%m%Y")) post.save_to_mongo()
def create_post(): post_data = request.get_json(force=True, silent=True) if post_data == None: return "Bad request", 400 post = Post(post_data["title"], post_data["content"]) post.save() return json.dumps(post.to_dict()), 201
def edit_post_service(post_id, new_title, new_body, new_tags): # Find logged user current_user = get_user_id(get_jwt_identity()) # Find a post post = Post.objects(id=post_id).first() # Find post author author = json.loads(json_util.dumps(post.to_mongo()))["author"]["$oid"] # Check if new title is repeated duplicated_post = Post.objects(title=new_title).first() if duplicated_post == post: duplicated_post = None if current_user is None: return Response("You have to log in first!", status=401) elif post is None: return Response("Cannot find post in database!", status=403) elif duplicated_post is not None: return Response(f"Post with title {new_title} already exists!", status=403) elif str(author) == str(current_user): post.title = new_title post.body = new_body post.tags = new_tags post.modified = True post.lastModifiedAt = datetime.utcnow post.save() return jsonify(post) else: return Response("Post cannot be updated!", status=409)
def test_14(self, m='Deleted post should be deleted'): p = Post({"title": "Another original post", "contents":"This is the content", "tags":"music,guitar,test", "author":"*****@*****.**"}) p.validate() p.save() retrieved_post = Post.get(p.pk()) retrieved_post.delete() retrieved_post.is_deleted() |should| equal_to(True) Post.get(p.pk()) |should| equal_to(None)
def get(self, **kwargs): post_id = kwargs['post_id'] Post.get_by_id(int(post_id)).key.delete() # Cascade the delete to all comments associated with the post comments = Comment.query(Comment.post_id == int(post_id)) for comment in comments: comment.key.delete() self.redirect('/')
def save_post(post: Post): try: table.put_item( Item=post.to_dict() ) except Exception as e: print(e) print(post) send_message('not-quite-dlq', post.to_json(), {"source": post.source})
def post(self, id): subject = self.request.get('subject') content = self.request.get('content') if subject and content: post = Post(subject=subject, content=content) key = post.put() self.redirect('/blog/' + str(key.id())) else: self.render_form(content, subject, 'Both a subject and content must be present')
def get(self, id): query = ( "SELECT id, publish_date, length, user, topic, thread, hash " "FROM post WHERE id=%s") cursor = self.db.cursor(query, (id)) sql_result = cursor.fetchone() cursor.close() post = Post(sql_result[1], sql_result[2], sql_result[3], sql_result[4]) post.id = sql_result[0] post.hash = sql_result[5] return post
def deleteURL(): if not session["logged_in"]: return redirect(url_for("index")) if request.method == 'POST': id = request.form['id'] post = Post(session["username"]) post.delete(id) return "Success"
def post(self, id): subject = self.request.get("subject") content = self.request.get("content") if subject and content: post = Post(subject=subject, content=content) key = post.put() self.redirect("/blog/" + str(key.id())) else: self.render_form(content, subject, "Both a subject and content must be present")
def get_modelled_list(self, posts): modelled_post_list = [] for post in posts: try: modelled_post = Post() modelled_post.id = post['_id'] date_obj = post['date'] modelled_post.date = date_obj.isoformat() # print post['title'] modelled_post.title = post['title'] modelled_post.link = post['link'] modelled_post.category = post['category'] modelled_post.tags = post['tags'] modelled_post.group = post['group'] modelled_post.added_by = post['added_by'] # print modelled_post.title modelled_post_list.append(modelled_post) # print "in", modelled_post_list except Exception as inst: print "error processing objects" print inst return None # print "out", modelled_post_list return modelled_post_list
def post(self, user_id): """ Make a new post """ args = postParser.parse_args() content = args['content'] profile = Profile.objects(user=user_id).first() post = Post(user=user_id, user_profile=profile, content=content) post.save() return {'status': 'success'}
def add_new_post_service(title, body, tags=None): # cannot add two posts with the same title if Post.objects(title=title).first() is None: current_user = get_jwt_identity() new_post = Post(title=title, body=body, tags=tags, author=get_user_id(current_user)) new_post.save() return jsonify(new_post) else: return Response("Post with that title already exist!", status=409)
def updateURL(): if not session["logged_in"]: return redirect(url_for("index")) if request.method == 'POST': id = request.form['id'] status = request.form['status'] post = Post(session["username"]) post.updateStatus(id, status) return "Success"
def create_post(): if request.method == 'GET': return render_template("new_post.html") elif request.method == 'POST': post_data = request.get_json(force=True, silent=True) if post_data == None: return "Bad request", 400 post = Post(post_data["title"], post_data["content"], post_data["price"], post_data["post_date"], post_data["available"], post_data["buyer"]) post.save() return redirect('/api/posts')
def post(self): titulo = self.request.get("edTitulo", "") autor = self.request.get("edAutor", "") contenido = self.request.get("edContenido", "") if (not titulo or not autor or not contenido): return self.redirect("/home") else: post = Post(titulo=titulo, contenido=contenido, autor=autor) post.put() time.sleep(1) return self.redirect("/home")
def addURL(): if not session["logged_in"]: return redirect(url_for("index")) if request.method == 'POST': url = request.form['url'] post = Post(session["username"]) count = len(post.get(user_id=session["user_id"]).all()) if count < post.limit: status = post.add(url) return status
def get(self, id): if id == 'newpost': self.render_form() elif str(id).isdigit(): p = Post.get_by_id([int(id)])[0] self.render('blog/post.html', post=p) elif re.match(r'\d+\.json', id): p = Post.get_by_id([int(str(id).split('.')[0])])[0] self.render_json(p.to_json()) elif str(id) == '.json': self.render_json(json.dumps(list(Post.select_all()), cls=ModelEncoder)) else: self.error(404)
def get(self, id): if id == "newpost": self.render_form() elif str(id).isdigit(): p = Post.get_by_id([int(id)])[0] self.render("blog/post.html", post=p) elif re.match(r"\d+\.json", id): p = Post.get_by_id([int(str(id).split(".")[0])])[0] self.render_json(p.to_json()) elif str(id) == ".json": self.render_json(json.dumps(list(Post.select_all()), cls=ModelEncoder)) else: self.error(404)
def create_post(): post = Post() try: data = request.get_data() data = json.loads(data) post.title = data['title'] post.content = data['content'] post.category_id = data['category_id'] tags = data['tags'] post.region = data['region'] post.image_header_id = data['image_header_id'] except Exception: raise ServiceException(ErrorCode.PARAM_ERROR, 'param error') tag_ids = [] if tags is not None and tags != '': tags = tags.split(",") for tag_name in tags: try: tag = GroupService.get_tag_by_name(tag_name) except ServiceException: tag = GroupService.insert_tag(tag_name) tag_ids.append(str(tag.id)) post.tag_ids = ",".join(tag_ids) post = PostService.insert_post(post) return jsonify(json_resp(data=model2dict(post)))
def update_post(): responseWrapper = ResponseWrapper() response = any_response(request) user = validate_cookie(request) if user != None: post = Post() try: # build post object from form data form_data = request.form['data'] json_data = json.loads(form_data) post.id = json_data['_id'] post.title = json_data['title'] post.link = json_data['link'] post.category = json_data['category'] post.tags = json_data['tags'] post.group = json_data['groups'] post.added_by = user.name except Exception as inst: print "error reading form data" print inst responseWrapper = ResponseWrapper() responseWrapper.set_error(True) responseWrapper.set_data(["error reading form data. Retry posting"]) if post.title != None and post.link != None and post.group != None and post.added_by != None: result = postDAO.update_post(post); responseWrapper = ResponseWrapper() if result != None or result != False: responseWrapper.set_error(False) responseWrapper.set_data([str(result)]) response.status_code = 201 else: responseWrapper.set_error(True) responseWrapper.set_data(["error writing post"]) else: print "error in form data" responseWrapper = ResponseWrapper() responseWrapper.set_error(True) responseWrapper.set_data(["insufficient fields, try again"]) response.status_code = 302 else: responseWrapper.set_error(True) responseWrapper.set_data(["User not logged in. Please Login"]) response.status_code = 302 response.data = json.dumps(responseWrapper, default=ResponseWrapper.__str__) response.mimetype = "application/json" return response
def save_from_form(self, save_status, save=True): """ Updates a post based on form values and notifies ping services if it is the first publication of the post """ do_notification = False tags = [] for tag in self.params.get('tags', "").split(','): tags.append(tag.strip()) if self.params.get('key'): # update if we have an id p = Post.get(self.params.get('key')) if save and p.status <> 'Published' and save_status == 'Published': do_notification = True p.content = self.params.get('content', None) p.title = self.params.get('title', None) p.status = save_status p.slug = self.params.get('slug', None) p.tags = tags else: # else we insert p = Post( content = self.params.get('content', None), title = self.params.get('title', None), status = save_status, slug = self.params.get('slug', None), tags = tags ) if save and save_status == 'Published': do_notification = True if save: p.put() archive = 'archive_' + str(p.posted_on.year) + str(p.posted_on.month) + str(p.posted_on.day) ptitle = str(p.posted_on.year).rjust(2, '0') + str(p.posted_on.month).rjust(2, '0') + str(p.posted_on.day).rjust(2, '0') + '/' + p.slug self.invalidate_cache(['blog_last10', archive, ptitle]) do_notification = False if do_notification: from external.notification import ping_all name = 'AlephNullPlex' base = 'http://alephnullplex.appspot.com/blog/' perm = base + 'view/' + str(p.posted_on.year) + str(p.posted_on.month) + str(p.posted_on.day)+ '/' + p.slug feed = base + 'rss' errors = ping_all(name, base, perm, feed, '') if errors: self.error = '<br />'.join(errors) return p
def new_post(self): title = input("Enter post title") content = input("Enter post content") date = input( "Enter post date, or leave blank for today(in format ddmmyyyy): ") if (date == ""): date = datetime.datetime.utcnow() else: date = datetime.datetime.strptime(date, "%d%m%Y") post = Post(blog_id=self.id, title=title, content=content, author=self.author, date=date) # strp allows to give a format string post.save_to_mongo()
def get(self): # Recuperamos el post para luego poder eliminarlo a través de su clave post = Post.recupera(self.request) post.key.delete() time.sleep(1) return self.redirect("/home")
def get(self): """ This renders home page with all posts, sorted by date. """ deleted_post_id = self.request.get('deleted_post_id') posts = greetings = Post.all().order('-created') self.render('front.html', posts=posts, deleted_post_id=deleted_post_id)
def testUnlikedPostCanBeLiked(self): # Ensure that post has been liked post = Post.get_by_id(self.initial_post_to_like_key.integer_id()) post.liked_by.append("Valid Liker") post.put() # Ensure that the Unlike button appears self.testapp.set_cookie('user', create_user_cookie('Valid Liker')) response = self.testapp.request( '/posts/%d' % self.initial_post_to_like_key.integer_id()) like_button = response.html.select('.post-like')[0] self.assertEqual(like_button.get_text(), 'Unlike') # Click the Unlike button an ensure the like counter decrements unlike_response = response.click(description="Unlike").follow() like_counter = unlike_response.html.select('.post-likes')[0].get_text() self.assertEqual(int(like_counter), 1) # Now ensure that there is a Like button and that re-liking # increments the counter re_like_response = unlike_response.click(description="Like").follow() re_like_counter = re_like_response.html.select( '.post-likes')[0].get_text() self.assertTrue(int(re_like_counter) == int(like_counter) + 1)
def post(self, **kwargs): title = self.request.POST['title'] content = self.request.POST['content'] submitter = self.request.cookies.get('user').split("|")[0] # Check that title and content are non-empty and add the data to the # datastore; otherwise, re-render the form with errors if title != '' and content != '': new_post = Post(title=title, content=content, submitter=submitter) new_post_key = new_post.put() new_post_id = new_post_key.id() self.redirect('/posts/%d' % new_post_id) else: template = jinja_env.get_template('new-post.html') form_data = {'title': title, 'content': content, 'error': True} self.write(template, {'form': form_data, 'new': True})
def get(self, **kwargs): template = jinja_env.get_template('post.html') post_id = kwargs['post_id'] post = Post.get_by_id(int(post_id)) # Retrieve all comments comments_query = Comment.query(Comment.post_id == int(post_id)).order( Comment.submitted) comments = [comment for comment in comments_query] # Discern anonymous browsers from users cookie = self.request.cookies.get('user') user = None has_liked = None if validate_user_cookie(cookie): user = cookie.split("|")[0] has_liked = user_has_liked_post(user, post_id) # If this post exists, render it (otherwise, 404) self.write( template, { 'post': post, 'comments': comments, 'current_user': user, 'has_liked': has_liked })
def __from_dynamo(item: dict) -> Post: return Post(name=item["name"]["S"], text=item["text"]["S"], post_id=item["post_id"]["S"], timestamp=item["timestamp"]["S"], img_url=item["img_url"]["S"], tags=item.get("tags", {}).get("SS"))
def get_post_service(post_id): # get post by id post = Post.objects(id=post_id).first() if post is not None: return post else: return Response("Post not found!", status=404)
def init_db(): session = Session() file = open('example.json', 'r', encoding='utf-8') data = json.load(file) file.close() for user in data['Users']: item = User(username=user['username']) session.add(item) for section in data['Sections']: item = Section(title=section['title']) session.add(item) for post in data['Posts']: item = Post(title=post['title'], section_id=post['section_id'], user_id=post['user_id'], description=post['description']) session.add(item) for tag in data['Tags']: item = Tag(name=tag['name'], post_id=tag['post_id']) session.add(item) session.commit() session.close()
def create(self, request, *args, **kwargs): try: serializer = self.get_serializer(data=request.data) if serializer.is_valid(): # 대댓글을 달 post, comment 확인 post_id = kwargs["post_id"] comment_id = kwargs["comment_id"] comment = Comment.objects.filter(id=comment_id, post_id=post_id, depth=1).first() if comment: sequence_max = Comment.objects.filter( group=comment.group, post_id=post_id).aggregate(Max('sequence')) sequence = sequence_max["sequence__max"] + 1 post = Post(id=post_id) Comment.objects.create(post=post, sequence=sequence, depth=2, group=comment.group, **request.data) return Response(status=200, data=serializer.data) else: # 데이터 없음 return Response(status=400, data="데이터 없음") else: return Response(status=400) except Exception as e: print(e) return Response(status=500)
def new_post(self): title = input("Enter post title : ") content = input("Enter Post content : ") date = input( "Enter the post date or leave blank for today (in format DDMMYYYY)" ) if date == "": date = datetime.datetime.utcnow() else: date = datetime.datetime.strptime(date, "%d%m%Y") post = Post(blog_id=self.id, title=title, content=content, author=self.author, date=date) post.save_to_mongo()
def update_permission(cls, post_id, update_info): """available_to_other #anonymous_to_other comment_permission title abstract """ return Post.update_other_info(post_id, **update_info)
def add(self, **kvals): if len(kvals): post = Post(kvals) post.validate() if post.is_valid(): post.save() return self.redirect("/post/%s" % post.pk()) else: post = Post() return self.render("post/add", post=post)
def edit(self, id=None, **kvals): post = Post.get(id) if len(kvals): post.update(kvals) post.validate() if post.is_valid(): post.save() return self.redirect("/post/%s" % post.pk()) return self.render("post/edit", post=post)
def add(): if request.method == 'POST': if not session.get('user_id'): abort(401) result = Post.add(1, request.form['blog_title'], request.form['blog_content']) flash('add success') return redirect(url_for('index')) else: return render_template('add.html')
def error_if_post_does_not_exist(*args, **kwargs): self = args[0] post_id = kwargs['post_id'] post = Post.get_by_id(int(post_id)) if post: fn(self, **kwargs) else: self.abort(404)
def post(self): title = self.request.get('title') content = self.request.get('content') board = self.request.get('board') if title == '': self.error(400) else: author = getSecureUser(self.request) if(author is not None): # TODO: check if user is authorized to post in board newPost = Post(title=title, content=content, author=author, board=board) newPost.put() # TODO: redirect to post URL else: self.error(401)
def get(self, id=None): if id is not None: # /post/{id}: Read data for specific post post = Post.get_by_id(int(id)) if post is not None: response = { 'id': post.key.id(), 'title': post.title, 'content': post.content, 'author': post.author, 'board': post.board, 'created': str(post.created), 'modified': str(post.modified) } self.response.write(json.dumps(response)) else: self.error(404) else: # /post: Read list of latest posts postsQuery = Post.query().fetch(25) posts = [] for post in postsQuery: posts.append({ 'id': post.key.id(), 'title': post.title, 'content': post.content, 'author': post.author, 'board': post.board, 'created': str(post.created), 'modified': str(post.modified) }) response = { 'posts': posts } self.response.write(json.dumps(response))
def get(self, user_id): """ Get posts by users """ args = postParser.parse_args() page = args['page'] if page is None: page = 0 posts = Post.objects().exclude('user')[10 * page: 10 * (page + 1)] if posts is None: return abort(400) return posts_list_serialize(posts)
def post(self): p = Post.get(self.params['post_key']) spam = self.params.get('spam_breaker', None) if not spam or spam.lower().find("purple") == -1: self.redirect('/blog/view/%s/%s' % (p.posted_on.strftime("%Y%m%d"), p.slug)) return c = Comment(post=p, author=self.params['author'], email=self.params.get('email', None), url=self.params.get('url', None), content=self.params['comment']) c.put() mailer.new_comment(p, c) self.redirect('/blog/view/%s/%s' % (p.posted_on.strftime("%Y%m%d"), p.slug))
def show(self): dstring = self.params.get('date', None) if dstring: # redirect them to the nicer /Y/m/d/slug url self.redirect('/blog/view/%s/%s/%s/%s' % (dstring[:4],dstring[4:6],dstring[6:], self.params['id'])) else: year = self.params["year"] month = self.params["month"] day = self.params["day"] posts = Post.get_archive(int(year), int(month), int(day)).filter('slug =', self.params['id']) p = self.from_cache(year + month + day + '/' + self.params['id'], lambda: posts.fetch(1)) if (len(p) > 0): self.post = p[0] else: self.render(template='../404')
def archives(self): year = self.params.get('year', None) month = self.params.get('month', None) day = self.params.get('day', None) key = 'archive_' + str(year) + str(month) + str(day) self.page(Post.get_archive(year, month, day).order('-posted_on'), key);
def rss(self): p = Post.all() p.order('-posted_on').filter('status =', 'Published') self.posts = self.from_cache('blog_last10', lambda: p.fetch(10))
def index(self): p = Post.all().order('-posted_on').filter('status =', 'Published') self.page(p, 'blog_index_page_')
def test_11(self, m="Validated Post should be able to save"): p = Post({"title": "This is the test", "contents":"This is the content", "tags":"music,guitar,test", "author":"*****@*****.**"}) p.validate() p.is_valid() |should| equal_to(True) len(p.errors()) |should| equal_to(0) p.save() |should_not| throw(ModelNotValid)
def test_12(self, m="Post should be retrieved by it's pk"): p = Post({"title": "This is the second test", "contents":"This is the content", "tags":"music,guitar,test", "author":"*****@*****.**"}) p.validate() p.is_new() |should| equal_to(True) p.save() p.is_new() |should_not| equal_to(True) retrieved_post = Post.get(p.pk()) retrieved_post |should| equal_to(p) retrieved_post.is_new() |should| equal_to(False)
def detail(blog_id): blog = Post.get(blog_id) return render_template('detail.html', blog=blog)
def edit(self): self.require_admin() try: self.post = Post.get(self.params['id']) except KeyError: self.post = None
def search(self): term = self.params.get('q', None) self.posts = Post.all().search(term).filter('status =', 'Published').order('-posted_on') self.has_results = self.posts.count() self.search_term = term
def test_01(self, m="Post should not validate without title, contents, tags and author"): p = Post({"title": "", "contents":"", "tags":"", "author":""}) p.validate() p.is_valid() |should| equal_to(False) len(p.errors()) |should| equal_to(4)
def test_09(self, m="Validated Post should set it's pk to time uuid"): p = Post({"title": "What's the best answe' for 1969", "contents":"This is the content", "tags":"music,guitar,test", "author":"*****@*****.**"}) p.validate() len(p.pk()) |should| equal_to(36) p.pk() |should| be_like('^[\w\d]{8}\-[\w\d]{4}\-[\w\d]{4}\-[\w\d]{4}\-[\w\d]{12}$')
def test_06(self, m="Post should validate"): p = Post({"title": "This is the test", "contents":"This is the content", "tags":"music,guitar,test", "author":"*****@*****.**"}) p.validate() p.is_valid() |should| equal_to(True) len(p.errors()) |should| equal_to(0)
def tag(self): p = Post.all().order('-posted_on').filter('tags =', self.params['id']).filter('status =', 'Published') self.tagged = self.params['id'] self.page(p, 'blog_tag_' + self.params['id'])
def index(): blogs = Post.get_list() return render_template('index.html', blogs=blogs)
def test_05(self, m="Post should not validate without author email"): p = Post({"title": "This is the test", "contents":"This is the content", "tags":"music,guitar,test", "author":"yanekk"}) p.validate() p.is_valid() |should| equal_to(False) len(p.errors()) |should| equal_to(1)
def test_01(self, m="Cassandra should enable finding posts by author"): yanekk_post = Post({"title": "This is the post by Yanekk", "contents":"yanekk yanekk yanekk", "tags":"music,guitar,test", "author":"*****@*****.**"}) yanekk_post.validate() yanekk_post.save() second_yanekk_post = Post({"title": "Another post by Yanekk", "contents":"yanekk yanekk yanekk", "tags":"music,guitar,test", "author":"*****@*****.**"}) second_yanekk_post.validate() second_yanekk_post.save() zbyszek_post = Post({"title": "Post by zbyszek", "contents":"yanekk yanekk yanekk", "tags":"music,guitar,test", "author":"*****@*****.**"}) zbyszek_post.validate() zbyszek_post.save() yanekk_posts = Post.by_index("author", "==", "*****@*****.**") zbyszek_posts = Post.by_index("author", "==", "*****@*****.**") yanekk_posts |should| contain(yanekk_post) yanekk_posts |should| contain(second_yanekk_post) yanekk_posts |should_not| contain(zbyszek_post) zbyszek_posts |should| contain(zbyszek_post) zbyszek_posts |should_not| contain(yanekk_post)