def post(self): """ New Bucketlist""" self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('title', type=str, required=True, help="Task title can't be blank", location='json') self.reqparse.add_argument('description', type=str, default="", location='json') args = self.reqparse.parse_args() title = args['title'] description = args['description'] user_id = g.user.user_id # check if title is null if title == "": # status code - Bad request return {'error': "Title can't be empty"}, 400 # testing if a bucketlist exists if BucketList.query.filter_by(title=title, created_by=user_id).first() is not None: # status code - request accepted but not processed return { 'message': 'BucketList - {} already exists'.format(title) }, 202 bucketlist = BucketList(title=title, description=description, created_by=user_id) db.session.add(bucketlist) db.session.commit() # status code - created new resource return { 'message': '{} - bucketlist has been added succesfully by {}'.format( title, g.user.username) }, 201
def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.drop_all() db.create_all() u = User(username=self.default_username) u.hash_password(self.default_password) u.save() g.user = u new_u = User(username=self.new_user) new_u.hash_password(self.default_password) new_u.save() bucketlist = BucketList(name=self.default_bucketlist) bucketlist.create() bucketlist.save() item = BucketItem(name=self.default_bucketlistitem, bucketlist_id=bucketlist.id) item.create() item.save() self.client = self.app.test_client()
def post(self, user_id): name = request.data.get("name", "").strip() if name: existing = BucketList.query.filter_by(name=name, created_by=user_id).first() if existing: response = {"message": "Bucketlist exists"} return make_response(jsonify(response)), 409 bucketlist = BucketList(name=name, created_by=user_id) bucketlist.save() response = jsonify({ "id": bucketlist.id, "name": bucketlist.name, "date_created": bucketlist.date_created, "date_modified": bucketlist.date_modified, "created_by": user_id }) return make_response(response), 201 response = {"message": "Bucketlist can not be blank name"} return make_response(jsonify(response)), 400
def bucketlists(): if request.method == 'POST': name = str(request.data.get('name', '')) if name: bucketlist = BucketList(name=name) bucketlist.save() response = jsonify({ 'id': bucketlist.id, 'name': bucketlist.name, 'date_created': bucketlist.date_created, 'date_modified': bucketlist.date_modified }) response.status_code = 201 return response else: # GET bucketlists = BucketList.get_all() results = list(map(lambda bucket: dict(id=bucket.id, name=bucket.name, date_created=bucket.date_created, date_modified=bucket.date_modified), bucketlists)) response = jsonify(results) response.status_code = 200 return response
def setUp(self): db.create_all(app=self.app_t) self.today = datetime.now().strftime('%Y-%m-%d') self.http = self.create_app().test_client() # Create and add a user to the db user = User(username='******', password=generate_password_hash('migwi123')) user.save() # Add a BucketList to the db bucketlist = BucketList(name='December Vacation', date_created=datetime.now(), date_modified=datetime.now(), created_by=1) bucketlist.save() # Add Items to the db # Task 1 tasks1 = Item(name='Visit Nigeria', bucketlist_id=1, date_created=datetime.now(), date_modified=datetime.now(), done=False) tasks1.save() # Task 2 tasks2 = Item(name='Visit New York', bucketlist_id=1, date_created=datetime.now(), date_modified=datetime.now(), done=False) tasks2.save() # Task 3 tasks3 = Item(name='Visit Las Vegas', bucketlist_id=1, date_created=datetime.now(), date_modified=datetime.now(), done=False) tasks3.save() query_user = User.query.filter_by(username='******').first() if query_user: user = {} user['username'] = '******' user['id'] = query_user.id token = generate_a_token(user) # retrieve a token ::: Token should not a contain password if token: self.auth_head = {'Authorization': 'Bearer %s' % token} else: log.error('No Token Was Generated') self.fail() # stop if a token generation failed # Add Other Users user = User(username='******', password=generate_password_hash('njirap123')) user.save() user = User(username='******', password=generate_password_hash('kimani123')) user.save() # Add a BucketList to the db bucketlist = BucketList(name='Visit Kenya', date_created=datetime.now(), date_modified=datetime.now(), created_by=1) bucketlist.save()
def setUp(self): self.bucketlist_instance = BucketList('Holiday', 'Let us travel the world')
def bucketlists(user_id, *args, **kwargs): if request.method == "POST": all_bucketlists = [ bucketlist.name for bucketlist in BucketList.query.filter_by( created_by=user_id) ] name = str(request.data.get("name", "")) if name and name not in all_bucketlists: bucketlist = BucketList(name=name, created_by=user_id) bucketlist.save() response = jsonify({ "id": bucketlist.id, "name": bucketlist.name, "date_created": bucketlist.date_created, "date_modified": bucketlist.date_modified, "created_by": user_id }) return make_response(response), 201 elif name in all_bucketlists: response = jsonify({"message": "Bucket List already exists"}) return make_response(response), 409 elif request.method == "GET": search_query = str(request.args.get("q", "")) if not search_query: # Paginate results for all bucketlists by default limit = request.args.get("limit") if request.args.get("page"): # Get the page requested page = int(request.args.get("page")) else: # If no page number request, start at the first one page = 1 if limit and int(limit) < 100: # Use the limit value from user if it exists limit = int(request.args.get("limit")) else: # Set the default limit value if none was received limit = 10 paginated_results = BucketList.query.filter_by( created_by=user_id).paginate(page, limit, False) if paginated_results.has_next: next_page = request.endpoint + '?page=' + str( page + 1) + '&limit=' + str(limit) else: next_page = "" if paginated_results.has_prev: previous_page = request.endpoint + '?page=' + str( page - 1) + '&limit=' + str(limit) else: previous_page = "" paginated_bucketlists = paginated_results.items # Return the bucket lists results = [] for bucketlist in paginated_bucketlists: # Get the items in the bucketlists searched items = Item.query.filter_by(bucketlist_id=bucketlist.id) items_list = [] for item in items: obj = { "id": item.id, "name": item.name, "date_created": item.date_created, "date_modified": item.date_modified, "done": item.done } items_list.append(obj) bucketlist_object = { "id": bucketlist.id, "name": bucketlist.name, "date_created": bucketlist.date_created, "date_modified": bucketlist.date_modified, "items": items_list, "created_by": bucketlist.created_by } results.append(bucketlist_object) response = { "next_page": next_page, "previous_page": previous_page, "bucketlists": results } return make_response(jsonify(response)), 200 elif search_query: # Paginate search results for bucket lists limit = request.args.get("limit") if request.args.get("page"): # Get the page requested page = int(request.args.get("page")) else: # If no page number request, start at the first one page = 1 if limit and int(limit) < 100: # Use the limit value from user if it exists limit = int(request.args.get("limit")) else: # Set the default limit value if none was received limit = 10 paginated_results = BucketList.query.filter( BucketList.name.ilike('%' + search_query + '%')).filter_by( created_by=user_id).paginate(page, limit, False) if paginated_results.items: if paginated_results.has_next: next_page = request.endpoint + '?q=' + search_query + \ '&page=' + str(page + 1) + '&limit=' + str(limit) else: next_page = "" if paginated_results.has_prev: previous_page = request.endpoint + '?q=' + search_query\ + '&page=' + str(page - 1) + '&limit=' + str(limit) else: previous_page = "" paginated_bucketlists = paginated_results.items # Return the bucket lists results = [] for bucketlist in paginated_bucketlists: # Get the items in the bucketlists searched items = Item.query.filter_by( bucketlist_id=bucketlist.id) items_list = [] for item in items: obj = { "id": item.id, "name": item.name, "date_created": item.date_created, "date_modified": item.date_modified, "done": item.done } items_list.append(obj) bucketlist_object = { "id": bucketlist.id, "name": bucketlist.name, "date_created": bucketlist.date_created, "date_modified": bucketlist.date_modified, "items": items_list, "created_by": bucketlist.created_by } results.append(bucketlist_object) response = { "next_page": next_page, "previous_page": previous_page, "bucketlists": results } return make_response(jsonify(response)), 200 # If there are no results after the search else: response = { "message": "No results found", "bucketlists": [] } return make_response(jsonify(response)), 404 else: # If the request was not a search results = [] for bucketlist in bucketlists: # Get the items in the bucketlists searched items = Item.query.filter_by(bucketlist_id=bucketlist.id) items_list = [] for item in items: obj = { "id": item.id, "name": item.name, "date_created": item.date_created, "date_modified": item.date_modified, "done": item.done } items_list.append(obj) bucketlist_object = { "id": bucketlist.id, "name": bucketlist.name, "date_created": bucketlist.date_created, "date_modified": bucketlist.date_modified, "items": items_list, "created_by": bucketlist.created_by } results.append(bucketlist_object) return make_response(jsonify(results)), 200
def bucketlists(): '''a method that will save a bucket list if post is chosen, return a bucketlist if GET is chosen, the buckest list returned can be thinned down by an id''' header = request.headers.get('Authorization') if not header: response = jsonify({'message': 'No authorisation header given'}) return make_response(response), 401 if ' ' not in header: response = jsonify({ 'message1': 'A space needs to exist between the Bearer and token.', 'message2': 'The authorization should be typed as the example below', 'example': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDMzNDUzMjIsInN1YiI6MiwiaWF0IjoxNTAzMzQxNzIyfQ.fCZ3ibX-vHQ5SKxYbrarQ0I8lvq5TgMt03A5vGlGhDE"' }) return make_response(response), 401 user_id = User.decode_token_to_sub(header) if not isinstance(user_id, int): response = { 'message': 'User id returned is not an int', 'userid': user_id } return make_response(jsonify(response)), 401 if request.method == "POST": if 'name' not in request.data.keys(): response = jsonify( {'message': 'The key variable name has not been entered!'}) return make_response(response), 400 name = str(request.data.get('name', '')) status_of_similarity = False bucketlists_to_be_checked = BucketList.query.filter_by( creator_id=user_id) for item in bucketlists_to_be_checked: if name.lower() == item.name.lower(): status_of_similarity = True if not status_of_similarity: bucket_object = BucketList(name=name, creator_id=user_id) bucket_object.save_bucket() response = jsonify({ 'id': bucket_object.id, 'name': bucket_object.name, 'date_created': bucket_object.date_created, 'date_modified': bucket_object.date_modified, 'creator_id': user_id }) return make_response(response), 201 else: response = jsonify({ 'message': 'A bucket list exists with a similar name of {}!'.format( name) }) return make_response(response), 409 else: bucket_name_to_search = request.args.get('q') limit_to_return = request.args.get('limit') no_argument_given = request.args if bucket_name_to_search == '': response = jsonify( {'message': 'The search parameter has no string in it'}) return make_response(response), 400 elif bucket_name_to_search: bucketlist_list = BucketList.query.filter_by( creator_id=user_id) buckets = [] for item in bucketlist_list: if bucket_name_to_search.lower() in item.name.lower(): a_bucket_object = { 'id': item.id, 'name': item.name, 'date_created': item.date_created, 'date_modified': item.date_modified, 'creator_id': item.creator_id } buckets.append(a_bucket_object) if len(buckets) > 0: response = jsonify(buckets) return make_response(response), 200 else: response = jsonify({ 'message': 'Name does not exist', }) return make_response(response), 200 elif limit_to_return: if int(limit_to_return) > 0: bucketlist_list = BucketList.query.filter_by( creator_id=user_id).limit(int(limit_to_return)) buckets = [] for item in bucketlist_list: a_bucket_object = { 'id': item.id, 'name': item.name, 'date_created': item.date_created, 'date_modified': item.date_modified, 'creator_id': item.creator_id } buckets.append(a_bucket_object) response = jsonify(buckets) return make_response(response), 200 elif int(limit_to_return) == 0: response = jsonify({'message': 'Zero returns no buckets'}) return make_response(response), 200 else: response = jsonify({ 'message': 'The value entered on limit is not suitable' }) return make_response(response), 400 elif len(no_argument_given) == 0: list_of_bucketlist = BucketList.query.filter_by( creator_id=user_id) bucketlist_objects_list = [] for item in list_of_bucketlist: a_bucket_object = { 'id': item.id, 'name': item.name, 'date_created': item.date_created, 'date_modified': item.date_modified, 'creator_id': item.creator_id, } bucketlist_objects_list.append(a_bucket_object) #converting the bucket list objec into JSON response = jsonify(bucketlist_objects_list) return make_response(response), 200 else: response = jsonify({ 'message': 'Wrong route given. Below are the right routes', 'GET all bucketlists for user': '******', 'search particular bucketlist': '/bucketlists/?q=<name of bucket>', 'enter a limt to bucket list returned': 'bucketlsits/?limit=<integer>' }) return make_response(response), 400
def bucketlists(): '''Route for bucketlist(POST) and (GET)''' time_now = datetime.now() if request.method == 'POST': bucklist_name = None if request.json: bucklist_name = request.json.get('name', None) if not bucklist_name: return return_response(dict(Error='Create Failed: %s' '' % ACCEPTED_INPUT_FORMAT), 400) all_current_bucketlist = BucketList.query.filter_by( created_by=g.user_id).all() bucketlist_names = [bucket.name for bucket in all_current_bucketlist] # check if the name was passed or exists new_items = None if bucklist_name not in bucketlist_names: b_list = BucketList(name=bucklist_name, date_created=time_now, date_modified=time_now, created_by=g.user_id) new_items = b_list.save() if new_items: return return_response(new_items.get(), 201) return return_response(dict(Message="Resource Created Successfully"), 201) if request.method == 'GET': return_bucketlists = {} limit = '20' if not request.args else request.args.get('limit', '20') limit = 20 if not limit.isdigit() else int(limit) if limit > 100: return return_response( dict(Error=('Get Failed: Only a maximum of 100 ' 'items can be retrieved at ago')), 400) page = '1' if not request.args else request.args.get('page', '1') page = 1 if not page.isdigit() else int(page) # equal to 1 by default # Pagination count = limit * (page - 1) base_query = (BucketList.query.filter_by(created_by=g.user_id). order_by(BucketList.id)) all_bucks = base_query.paginate(page, limit, False).items # searching a word in bucketlist names q = '' if not request.args else request.args.get('q', None) if q: base_query = BucketList.query.filter(BucketList.name.contains(q)) all_bucks = base_query.filter_by(created_by=g.user_id).all() if not all_bucks: return return_response( dict(Error=('Get Failed: No Bucketlists Found.')), 400) for bucket_l in all_bucks: items = Item.query.filter_by(bucketlist_id=bucket_l.id).all() bucketlists = bucket_l.get() bucketlists['item'] = Item().get_all(items) count += 1 return_bucketlists[count] = bucketlists return return_response(return_bucketlists, 200)