Exemple #1
0
    def post(self, id):
        data = request.get_json()
        now = datetime.datetime.now()

        bucketlist = Bucketlist.query.filter_by(id=id).first()
        bucketlist_item = BucketlistItem.query.filter_by(
            item_name=data.get('item_name')).first()

        if not bucketlist_item:

            new_item = BucketlistItem(item_name=data.get('item_name'),
                                      bucketlist_id=bucketlist.id,
                                      date_created=now,
                                      date_modified=now,
                                      done=False,
                                      complete_by=data.get('complete_by'))
            new_item.save()

            response = jsonify({
                'status': "Success",
                'message': "Bucketlist Item Created"
            })

            response.status_code = 201

        else:
            response = jsonify({
                'status': "Fail",
                'message': "Bucketlist Item Already Exists"
            })

            response.status_code = 409  # 409 means there is a conflict with db as two of the same resource exists

        return make_response(response)
Exemple #2
0
    def delete(self, id, item_id):

        current_user = get_jwt_identity()

        bucketlist_item = BucketlistItem.get_bucketlist_items(
            id, item_id, current_user)

        if bucketlist_item:

            BucketlistItem.delete(bucketlist_item)

            response = jsonify({})

            response.status_code = 204  # Status 204 does not need a message body

        else:
            response = jsonify({
                "status":
                "Fail",
                "message":
                "Bucketlist item cannot be deleted as it does not exist"
            })

            response.status_code = 404

        return make_response(response)
    def post(self, request, **kwargs):

        bucketlistid = self.kwargs.get('id')
        itemname = request.POST.get('itemname', '')
        done = request.POST.get('done')
        done = True if done else False

        if itemname:
            items = BucketlistItem(
                name=itemname,
                done=done,
                bucketlist_id=bucketlistid)
            items.save()

            msg = "Item succesfully added."
            messages.add_message(request, messages.SUCCESS, msg)
            return HttpResponseRedirect(
                reverse_lazy('view',
                             kwargs={'id': bucketlistid}))

        else:
            msg = "field should not be submitted empty."
            messages.add_message(request, messages.SUCCESS, msg)
            return HttpResponseRedirect(reverse_lazy('view', kwargs={
                'id': bucketlistid}))
    def post(self, request, id):
        '''create a bucketlist item'''
        # get the bucketlist object
        bucketlist = get_object_or_404(Bucketlist, pk=id)

        # validate form
        form = CreateBucketlistForm(request.POST)

        if form.is_valid():
            item_name = form.cleaned_data['name']

            # create and save bucketlist item
            item = BucketlistItem(name=item_name, bucketlist=bucketlist)
            item.save()

            # create success message
            messages.add_message(request,
                                 messages.INFO,
                                 'Bucketlist item created')
        else:
            # send back form errors as messages
            for error in form.errors:
                messages.add_message(request,
                                     messages.ERROR,
                                     form.errors[error])
        return HttpResponseRedirect(reverse('frontend:bucketlist_items', kwargs={'id': id}))
Exemple #5
0
    def post(self, request, **kwargs):
        bucketitem_name = request.POST.get('name')
        if not bucketitem_name:
            messages.error(request,
                           'You attempted to enter an unnamed bucketitem')
            # returns error if trying to add an empty item
            return render(request, 'bucketlist/errors.html')

        bucketitem = BucketlistItem(
            name=bucketitem_name,
            bucketlist=BucketList.objects.get(pk=kwargs['bucketlistid']))

        bucketitem.save()

        messages.success(request, 'Successfully added an item!')
        return redirect('/bucketlist',
                        context_instance=RequestContext(request))
Exemple #6
0
def new_item(bucket_id):
    """
    Creates a new bucketlist item.
    """
    # check if bucketlist exists, then validate user input using try-catch block
    bucketlist = Bucketlist.query.filter_by(id=bucket_id,
                                            created_by=g.user.id).first()
    if not bucketlist:
        return jsonify(
            {"Message": "The bucketlist was not found. Please try again"}), 404
    else:
        try:
            item = BucketlistItem()
            sanitized = item.import_data(request.json)
            if sanitized == "Invalid":
                return jsonify({"Message": "The item must have a name"}), 400
        except ValidationError as e:
            return jsonify({"Message": str(e)}), 400

        # check for duplicates before creating the new item
        duplicate = BucketlistItem.query.filter_by(name=item.name,
                                                   bucket=bucket_id).first()
        if not duplicate:
            item.bucket = bucket_id
            item.created_by = g.user.id
            db.session.add(item)
            db.session.commit()
            return jsonify({
                "Message": item.name.title() + " has been created",
                "View it here": item.export_data()
            }), 201
        return jsonify({
            "Message":
            "A bucketlist item with that name already exists. Please try again"
        }), 400
    def post(self, request, **kwargs):
        bucketitem_name = request.POST.get('name')
        if not bucketitem_name:
            messages.error(
                request,
                'You attempted to enter an unnamed bucketitem')
            # returns error if trying to add an empty item
            return render(request, 'bucketlist/errors.html')

        bucketitem = BucketlistItem(
            name=bucketitem_name,
            bucketlist=BucketList.objects.get(
                pk=kwargs['bucketlistid']))

        bucketitem.save()

        messages.success(
            request, 'Successfully added an item!')
        return redirect(
            '/bucketlist',
            context_instance=RequestContext(request)
        )
    def post(self, request, **kwargs):

        bucketlistid = self.kwargs.get('id')
        itemname = request.POST.get('itemname', '')
        done = request.POST.get('done')
        done = True if done else False

        if itemname:
            items = BucketlistItem(name=itemname,
                                   done=done,
                                   bucketlist_id=bucketlistid)
            items.save()

            msg = "Item succesfully added."
            messages.add_message(request, messages.SUCCESS, msg)
            return HttpResponseRedirect(
                reverse_lazy('view', kwargs={'id': bucketlistid}))

        else:
            msg = "field should not be submitted empty."
            messages.add_message(request, messages.SUCCESS, msg)
            return HttpResponseRedirect(
                reverse_lazy('view', kwargs={'id': bucketlistid}))
Exemple #9
0
    def setUp(self):
        """
        Add bucketlists and items directly to db to avoid using tokens 
        required for POST request.
        """
        app.config.from_object(TestingConfig)
        self.client = app.test_client()
        db.create_all()

        self.client.post("/auth/register",
                         data=json.dumps(
                             dict(username="******", password="******")),
                         content_type="application/json")

        response = self.client.post("/auth/login",
                                    data=json.dumps(
                                        dict(username="******",
                                             password="******")),
                                    content_type="application/json")
        response_msg = json.loads(response.data)
        self.token = response_msg["Token"]

        bucket = {"name": "testbucketlist"}
        test_bucket = Bucketlist()
        test_bucket.import_data(bucket)
        test_bucket.created_by = 1

        bucket2 = {"name": "testbucketlist2"}
        test_bucket2 = Bucketlist()
        test_bucket2.import_data(bucket2)
        test_bucket2.created_by = 1

        bucket3 = {"name": "testbucketlist3"}
        test_bucket3 = Bucketlist()
        test_bucket3.import_data(bucket3)
        test_bucket3.created_by = 2

        item = {"name": "testitem", "done": ""}
        test_item = BucketlistItem()
        test_item.import_data(item)
        test_item.bucket = 1
        test_item.created_by = 1

        db.session.add(test_bucket)
        db.session.add(test_bucket2)
        db.session.add(test_bucket3)
        db.session.add(test_item)
        db.session.commit()
Exemple #10
0
    def put(self, id, item_id):
        data = request.get_json()

        current_user = get_jwt_identity()

        bucketlist_item = BucketlistItem.get_bucketlist_items(
            id, item_id, current_user)

        if bucketlist_item:
            bucketlist_item.item_name = data.get('item_name')

            if data.get('done') == 'true':

                bucketlist_item.done = True

            bucketlist_item.date_modified = datetime.datetime.now()
            database.session.commit()  # update new changes

            response = jsonify({
                "status":
                "Success",
                "message":
                "Bucketlist item successfully updated"
            })

            response.status_code = 200

        else:
            response = jsonify({
                "status": "Fail",
                "message": "Bucketlist item does not exist"
            })

            response.status_code = 404

        return make_response(response)
Exemple #11
0
    def get(self, **kwargs):

        start = request.args.get('start')
        limit = request.args.get('limit')
        query = request.args.get('q')

        current_user = get_jwt_identity()

        if kwargs.get('id') is not None and kwargs.get('item_id') is not None:

            buckelist_item = BucketlistItem.get_bucketlist_items(
                kwargs['id'], kwargs['item_id'], current_user)

            if buckelist_item:

                response = jsonify({
                    'item_name':
                    buckelist_item.item_name,
                    'date_created':
                    buckelist_item.date_created,
                    'date_modified':
                    buckelist_item.date_modified,
                    'done':
                    buckelist_item.done,
                    'complete_by':
                    buckelist_item.complete_by,
                    'bucketlist_id':
                    buckelist_item.bucketlist_id
                })
                response.status_code = 200

            else:

                response = jsonify({
                    "status":
                    "Fail",
                    "message":
                    "That bucketlist item does not exist in bucketlist"
                })
                response.status_code = 404

        elif kwargs.get('id') is not None:

            if start is None:
                start = 1

            if limit is None:
                limit = 5

            search = get_paginated_list(
                '/v1/api/bucketlists/' + str(kwargs['id']) + '/items/',
                'bucketlist_item', query, current_user, kwargs['id'],
                int(start), int(limit))

            try:
                all_items = []
                for buckelist_item in search['results']:
                    item_response = {
                        'item_name': buckelist_item.item_name,
                        'date_created': buckelist_item.date_created,
                        'date_modified': buckelist_item.date_modified,
                        'done': buckelist_item.done,
                        'complete_by': buckelist_item.complete_by,
                        'bucketlist_id': buckelist_item.bucketlist_id
                    }
                    all_items.append(item_response)

                response = jsonify({
                    "previous": search['previous'],
                    "next": search['next'],
                    "results": all_items
                })
                response.status_code = 200

            except:
                response = jsonify({
                    "status":
                    "Fail",
                    "message":
                    "No bucketlist item matching your query in exists"
                })
                response.status_code = 404

        return make_response(response)