def post(self, request): name = request.POST.get("name") url = request.POST.get("imgURL") caption = request.POST.get("caption") post = Post(imgURL=url, caption=caption, postedBy=name) post.save() return HttpResponseRedirect("/")
def create_blog_post(data): title = data.get('title') body = data.get('body') category_id = data.get('category_id') category = Category.query.filter(Category.id == category_id).one() post = Post(title, body, category) post.author = data.get('author') db.session.add(post) db.session.commit()
def post(self, request): if request.user.is_authenticated: title = request.POST.get("title") body = request.POST.get("body") name = request.user.username post = Post(title=title, body=body, postedBy=name, type="txt") post.save() return HttpResponseRedirect("/") return HttpResponseRedirect("/accounts/login")
def post(self, request): if request.user.is_authenticated: title = request.POST.get("title") url = request.POST.get("url") name = request.user.username post = Post(title=title, url=url, postedBy=name, type="lnk") post.save() return HttpResponseRedirect("/") return HttpResponseRedirect("/accounts/login")
def post(self): user_id = get_jwt_identity() body = request.get_json() user = User.objects.get(id=user_id) post = Post(**body, author=user) post.save() #user.update(push__post=post) user.save() id = post.id return {'id': str(id)}, 200
def notice_submit(request): if request.method == 'POST': title=request.POST['title'] body=request.POST['body'] date=datetime.datetime.now() new_notice = Post(title=title,body=body,date=date) new_notice.save() messages.success(request, "Success ! You are done !") return HttpResponseRedirect("/")
def addpost(req): # print(req.user.) if not req.user.is_authenticated: return Http404() data = req.body.decode('utf8') data = json.loads(data) title = data.get('title') content = data.get('content') reply = Post(by = req.user, title = title, content = content) reply.save() return JsonResponse({'status' : True})
async def get_all(conn, data): # query chaining not working if data.get('limit') and data.get('offset'): query = Post.select().order_by(Post.c.last_updated.desc()).limit(data['limit']).offset(data['offset']) elif data.get('limit'): query = Post.select().order_by(Post.c.last_updated.desc()).limit(data['limit']) elif data.get('offset'): query = Post.select().order_by(Post.c.last_updated.desc()).offset(data['offset']) else: query = Post.select().order_by(Post.c.last_updated.desc()) result = await conn.execute(query) return await result.fetchall()
def mutate(self, info, data): """Mutate method.""" user = User.query.filter_by(username=data['username']).first() if user is None: raise GraphQLError('User not found.') post = Post(title=data['title'], body=data['body']) post.author = user db.session.add(post) db.session.commit() return CreatePosts(post=post)
def create_post(user_id, lat, lon, body, artist, img_url="null"): p = Post(user_id, lat, lon, body, img_url) db_session.add(p) # make sure we update our database is updated with the id db_session.flush() db_session.commit() return {'success': 1, 'id': p.id, 'msg': 'success'}
def save_post(title, content): # Create the new post new_post = Post(title=title, content=content, date=datetime.datetime.now()) # Add and Save the new post db_session.add(new_post) db_session.commit()
def get(self): try: posts = Post.objects().to_json() return Response(posts, mimetype="application/json", status=200) except DoesNotExist: raise NotExistsError except Exception: raise InternalServerError
async def add_post(conn, data: Dict[str, str]): stmt = Post.insert().values(category_id=data['category_id'], title=data['title'], text=data['text'], main_img=data['main_img'], created_at=data['created_at'], last_updated=data['last_updated']) await conn.execute(stmt)
def post(self): """Save post into database.""" post_data = flask.request.json creator = User.query.get(flask.g.user_id) new_post = Post.create(creator=creator, **post_data) new_post.commit() avoid_fields = ('modified_at',) return flask.jsonify(new_post.instance_to_dict(avoid_fields))
def post(self): try: body = request.get_json() post = Post(**body).save() id = post.id return {'id': str(id)}, 200 except (FieldDoesNotExist, ValidationError): raise SchemaValidationError except NotUniqueError: raise AlreadyExistsError except Exception as e: raise InternalServerError
def post(self): try: user_id = get_jwt_identity() user = User.objects.get(id=user_id) body = { 'title': request.form['title'], 'content': request.form['content'], 'hashtags': request.form.getlist('hashtags[]') } post = Post(**body, author=user) post.save() if request.files and 'file' in request.files: file = request.files['file'] filename = str(post.id) + file.filename if save_file(filename, file): post.update(set__image=filename) socketio.emit('update', {}, room='mentor' + str(user.id)) return {'id': str(post.id)}, 200 except (FieldDoesNotExist, ValidationError): raise SchemaValidationError except DoesNotExist: raise DocumentMissing except Exception as e: raise InternalServerError
def parse_post(post): # parse into datetime object # EX 21-May-2019_21:24:15 datetime_obj = datetime.strptime(post["metadata"]["Date"], '%d-%b-%Y_%H:%M:%S') markdown_content = post["content"] title = post["title"] ## Debug ''' print ("Title: " + title) print ("Date: " + str(datetime_obj)) print ("Content: " + markdown_content) ''' new_post = Post(title = title, content = markdown_content, date = datetime_obj) return new_post
def get(self, current_user, public_post_id): post = Post.get_post_by_public_id(public_post_id) if not post: return {'success': False, 'error_code': 13, 'message': 'No post found with this id'}, 401 post, errors = PostSchema(only=('public_post_id', 'content', 'posted_at', 'public_user_id').dump(post)) if errors: print(errors) return {'success': False, 'error_code': 10, 'message': 'There was some error fetching the data'}, 401 return post
def get(self): try: user_id = get_jwt_identity() user = User.objects.get(id=user_id) ids = user.following ids.append(user) posts = Post.objects(author__in=ids) posts = [convert_post(ob) for ob in posts] posts.sort(key=operator.itemgetter('created_at'), reverse=True) return Response(JSONEncoder().encode(posts), mimetype="application/json", status=200) except DoesNotExist: raise DocumentMissing except Exception as e: raise InternalServerError
def main(): # Remember the last post for each subreddit # in order to not retrieve the same posts again last_post = {} subreddits = _config.get('subreddits', []) while True: for sr in subreddits: subreddit = _reddit_client.get_subreddit(sr) # Get latests posts for this subreddit post_models = [] for post in subreddit.get_new( limit=_config.get('posts-limit', 1), params={"before": last_post.get(sr)} ): post_models.append(Post(post)) # Get comments associated with this post comment_models = [] post.replace_more_comments(limit=16, threshold=10) for comment in praw.helpers.flatten_tree(post.comments): comment_models.append(Comment(comment, subreddit=sr)) # Insert comments try: _mongo.insert_many(comment_models) except: _log.error('Unable to insert comments', exc_info=True) # Remember last post to not fetch it again last_post[sr] = post.fullname # Insert post try: _mongo.insert_many(post_models) except: _log.error('Unable to insert posts', exc_info=True) # Request limiter time.sleep(_config.get('rate-limit', 1))
# Routers provide an easy way of automatically determining the URL conf. replies = getSerializers(dname = "replies", dmodel = Reply, dfields = ('id','comment', 'by', 'content', 'created_at', 'modified_at'), pred = lambda x: Reply( by = User.objects.get(id = x['by']), comment = Comment.objects.get(id = x['comment']), content = x['content'] ) ) posts = getSerializers(dname = "posts", dmodel = Post, dfields = ('id', 'by', 'content','title', 'created_at', 'modified_at'), pred = lambda x: Post( by = User.objects.get(id = x['by']), content = x['content'] ) ) comments = getSerializers(dname = "comments", dmodel = Comment, dfields = ('id','post', 'by', 'content', 'created_at', 'modified_at'), pred = lambda x: Comment( by = User.objects.get(id = x['by']), post = Post.objects.get(id = x['post']), content = x['content'] ) ) router = [replies, comments, posts] def loggedIn(req):
def get(self): posts = Post.objects().to_json() return Response(posts, mimetype="application/json", status=200)