class PostsEP(Resource): def __init__(self): self.post_schema = PostSchema() self.post_search_schema = PostSearchSchema() self.post_request = PostRequest() self.user_schema = PublicUserSchema() self.search_request = SearchRequest() self.items_per_page = 6 super(PostsEP, self).__init__() @Auth.authentication_required() def post(self): args = self.post_request.load(request.get_json()) if args.errors: raise exceptions.InvalidRequest(args.errors) uid = request.headers['UID'] try: user_object = User.objects.get(uid=uid) except User.DoesNotExist: raise exceptions.UserDoesNotExist("User Does Not Exist") if "url" in args.data: post_object = Post.objects.create( user=user_object, title=args.data['title'], url=args.data['url'], description=args.data['description'], tags=[Tag.get_or_create(tag['text']) for tag in args.data['tags']] ) else: post_object = Post.objects.create( user=user_object, title=args.data['title'], description=args.data['description'], tags=[Tag.get_or_create(tag['text']) for tag in args.data['tags']] ) response_post = self.post_schema.dump(post_object) return jsonify({"post": response_post.data}) @Auth.authentication_required() def get(self): args = self.search_request.load(request.args) if args.errors: raise exceptions.InvalidRequest(args.errors) if "search_field" in args.data: search_text = args.data['search_field'] search_result = Post.objects.search_text(search_text).order_by('$weights') result_length =len(search_result) offset = (args.data['page'] - 1) * self.items_per_page paginate_search_results = search_result.skip(offset).limit(self.items_per_page) else: offset = (args.data['page'] - 1) * self.items_per_page result_length = len(Post.objects()) paginate_search_results = Post.objects.order_by('-created').skip(offset).limit(self.items_per_page) response_posts = [] for post in paginate_search_results: post_dic = self.post_search_schema.dump(post).data post_dic['rating'] = post.get_rating() response_posts += [post_dic] return jsonify({"posts": response_posts, "items": result_length})
def __init__(self): self.post_schema = PostSchema() self.post_search_schema = PostSearchSchema() self.post_request = PostRequest() self.user_schema = PublicUserSchema() self.search_request = SearchRequest() self.items_per_page = 6 super(PostsEP, self).__init__()