Пример #1
0
 def post(self, request):
     " Adding a new todo." ""
     data = request.data
     user = request.user
     t = Todo(user=user,
              bucket=data['bucket'],
              description=data['description'],
              done=False)
     t.save()
     request.data['id'] = t.pk  # return id
     return Response(request.data, status=status.HTTP_201_CREATED)
Пример #2
0
 def put(self, request):
     """ Update a todo """
     data = request.data
     todo_id = data['id']
     desc = data['description']
     done = data['done']
     bucket = data['bucket']
     t = Todo(id=todo_id, bucket= bucket, user=str(request.user), description=desc,\
              done=done, updated=datetime.now())
     t.save()
     return Response(status=status.HTTP_200_OK)
Пример #3
0
    def post(self):
        '''Create a new todo'''
        parser = reqparse.RequestParser()
        parser.add_argument('todo', type=dict, required=True)
        args = parser.parse_args()

        if args['todo']['description']:
            todo = Todo(args['todo']['description'])
            db.session.add(todo)
            db.session.commit()
            return {'todo': todo.as_json()}
        restful.abort(400, message='Missing description')
Пример #4
0
 def mutate(self, info, body, complete):
     db_session = info.context['session']
     new_todo = Todo(body=body, complete=complete)
     db_session.add(new_todo)
     db_session.flush()
     db_session.refresh(new_todo)
     return CreateTodo(todo=new_todo)
Пример #5
0
def create_todo(json_resp, response):
    valid = True
    success = True
    new_todo = Todo()
    for key in json_resp:
        if hasattr(new_todo, key):
            setattr(new_todo, key, json_resp[key])
        else:
            valid = False
            # response['status'] = 400
            reason = "Todo does not have attribute: %s" % key
            error_obj = build_error_obj(status=404,
                                        code="Failed",
                                        title="Invalid attribute",
                                        detail=reason)
            response['errors'].append(error_obj)

    if valid:
        valid, response = validate_new_todo(new_todo, response)

    if valid:
        try:
            new_todo.save()
        except:
            success = False
            reason = "Unable to create todo"
            error_obj = build_error_obj(status=404,
                                        code="Failed",
                                        title="Unable to create",
                                        detail=reason)
            response['errors'].append(error_obj)

        if success:
            # response['status'] = 201
            for key in json_resp:
                response['data'][key] = json_resp[key]
            response.pop("errors", None)
        else:
            # response['status'] = 500
            response['code'] = "Failed"
            response.pop('data', None)
    else:
        # response['status'] = 400
        response['code'] = "Failed"
        response.pop("data", None)

    return response
Пример #6
0
def test_can_list_todos(db_session):
    """ Test wether a whole list of todos can be added to db and correctly
    retrieved by getting all entries from databse
    """
    todo_list = [
        Todo(name='Cleaning', date=parse('2019-04-23 12:00:00')),
        Todo(name='Homework', date=parse('2019-04-23 14:00:00'))
    ]

    db_session.add_all(todo_list)
    db_session.commit()
    results = db_session.query(Todo).all()

    assert len(results) == len(todo_list)

    for i in range(len(results)):
        assert results[i] == todo_list[i]
Пример #7
0
def create_todo(current_user):
    data = request.get_json()

    new_todo = Todo(text=data['text'], complete=False, user_id=current_user.id)
    db.session.add(new_todo)
    db.session.commit()

    return jsonify({'message': 'New todo created!'})
Пример #8
0
def add_todo(request):
    data = request.POST
    todo = Todo()
    todo.title = data.get('title', '')
    todo.deadline = data.get('deadline', '')
    todo.save()
    return JsonResponse(todo.to_json(), status=201)
Пример #9
0
def resolve_create_todo(obj, info, description, due_date):
    try:
        due_date = datetime.strptime(due_date, '%d-%m-%Y').date()
        todo = Todo(description=description, due_date=due_date)
        db.session.add(todo)
        db.session.commit()
        payload = {"success": True, "todo": todo.to_dict()}
    except ValueError:  # date format errors
        payload = {
            "success":
            False,
            "errors": [
                f"Incorrect date format provided. Date should be in "
                f"the format dd-mm-yyyy"
            ]
        }

    return payload
Пример #10
0
def api_create_todo_view(request):

    todo = Todo()

    if request.method == 'POST':
        serializer = TodoSerializer(todo, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({'status':'success'}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Пример #11
0
def add_todo(current_user):
    data = request.get_json()

    todo = Todo(description=data['description'],
                complete=False,
                user_id=current_user.public_id)

    db.session.add(todo)
    db.session.commit()

    result = todo_schema.dump(todo)

    return jsonify({'msg': 'Todo Created', 'Todo': result})
Пример #12
0
def index(request):
    tasks = Todo.objects.all()
    default_status = False
    if request.method == 'POST':
        if request.POST.get("save"):
            for i in tasks:
                if request.POST.get(str(i.id)) == "clicked":
                    i.completed = True
                else:
                    i.completed = False
                i.save()

        elif request.POST.get("delete") == "delete":
            for i in tasks:
                i.delete()

        else:
            new_task = Todo(title=request.POST['title'],
                            completed=default_status)
            new_task.save()

        return redirect('/')

    return render(request, 'index.html', {'tasks': tasks})
Пример #13
0
    def add(self, request):
        """
        Method for adding a new todo to the database via POST request

        Example request ::

            {
                "name": "EnglishLesson",
                "date": "2017-01-12 12:00:00"
             }


        The response contains the posted data with the parsed date and an added id column ::

            {
                "id" : 1,
                "name": "EnglishLesson",
                "date": "2017-01-12T12:00:00+00:00"
            }
        """

        dict = json.loads(request.get_data(as_text=True))

        try:
            #Get the name and date values from request. This might raise KeyError
            name = dict['name']
            date = dict['date']

            #If date value is a string try converting to datetime. This might raise Value Error
            if isinstance(date, str):
                date = parse(date)

            #Create SQL Alchemy Todo Object and add new entry to the database
            obj = Todo(name=name, date=date)
            schema = TodoSchema()
            session = self.db.get_session()
            session.add(obj)
            session.commit()

            #Prepare response data using marshmallow schema
            response = json.dumps(schema.dump(obj).data)
            session.close()
            return 201, response

        # Handle errors resulting from invalid data in the request
        except (ValueError, KeyError):
            return 400, 'Bad Request'
Пример #14
0
def create_update(request):
    title = request.POST.get('title')
    if not title:
        return redirect(reverse('web:index'))

    # get priority if supplied
    if title.strip().endswith('!'):
        priority = Todo.HIGH
        title = title.strip()[:-1].strip()
    else:
        priority = Todo.LOW

    # get date if defined
    if '^' in title:
        date = title.split('^')[1].split()[0]
        title = title.split('^')[0].strip()

        # parse date to datetime object
        date = timezone.datetime.strptime(date, '%m/%d/%Y')
    else:
        date = None

    todo_id = request.POST.get('todo_id')
    if todo_id:
        todo = get_object_or_404(Todo, id=todo_id)
    else:
        todo = Todo()
        todo.owner = request.user
        todo.completed = False

    todo.title = title
    todo.priority = priority
    todo.due_date = date
    todo.save()

    return redirect(reverse('web:index'))
Пример #15
0
def todo(request):
    """ Pytest fixture to create Todo model instance from each of the test cases
    """
    return Todo(name=request.param[0], date=request.param[1])
Пример #16
0
from django.contrib.auth.models import User
from api.models import Todo

# usr = User.objects.get(id=1)

todo_1 = Todo(title="First things first")
todo_1.save()

todo_2 = Todo(title="Finish first thing", is_completed=True)
todo_2.save()

todo_3 = Todo(title="Do other things")
todo_3.save()
Пример #17
0
def TodoView(request, todo_id=None):

    if request.method == 'GET' and request.resolver_match.url_name == 'todos':
        todos = Todo.objects.filter(user=request.user).order_by('-updated_at')
        todo_serializer = TodoListSerializer(todos, many=True)
        return Response(todo_serializer.data, status=200)

    if request.method == 'GET' and request.resolver_match.url_name == 'shared_todos':
        todos = Todo.objects.filter(assigned_users=request.user)
        todo_serializer = TodoListSerializer(todos, many=True)
        return Response(todo_serializer.data, status=200)

    if request.method == 'GET' and request.resolver_match.url_name == 'todo':

        if not todo_id:
            return Response({'error': 'Todo id is missing'}, status=400)

        try:
            todo = Todo.objects.get(id=todo_id)
        except Todo.DoesNotExist:
            return Response({'error': 'Not Found Todo'}, status=404)

        if todo.user != request.user and not todo.assigned_users.filter(
                username=request.user.username).exists():
            return Response({'error': 'Permission Denied'}, status=403)

        todo_serializer = TodoSerializer(todo, many=False)

        return Response(todo_serializer.data, status=200)

    if request.method == 'PUT' and request.resolver_match.url_name == 'todos':

        _id = request.data.get('id', None)
        title = request.data.get('title', None)
        status = request.data.get('status', False)
        content = request.data.get('content', '')

        if not title:
            return Response({'error': 'Title is missing'}, status=400)

        if _id:  # For Update
            try:
                todo = Todo.objects.get(id=_id)
            except Todo.DoesNotExist:
                return Response({'error': 'Todo not Found'}, status=404)

            if todo.user != request.user and not todo.assigned_users.filter(
                    username=request.user.username).exists():
                return Response({'error': 'Permission Denied'}, status=403)
        else:
            todo = Todo()

        if not _id:
            todo.user = request.user

        todo.title = title
        todo.content = content
        todo.status = status
        todo.updated_at = timezone.now()
        if not _id:
            todo.created_at = timezone.now()

        todo.save()
        return Response({
            'success': 'todo is created',
            'id': todo.id
        },
                        status=201)

    if request.method == 'POST' and request.resolver_match.url_name == 'users':

        if not todo_id:
            return Response({'error': 'Todo id is missing'}, status=400)

        try:
            todo = Todo.objects.get(id=todo_id)
        except Todo.DoesNotExist:
            return Response({'error': 'Not Found Todo'}, status=404)

        if todo.user != request.user:
            return Response({'error': 'Permission Denied'}, status=403)

        usr_email = request.data.get('email', None)

        if not usr_email:
            return Response({'error': 'User is missing'}, status=400)

        try:
            user = User.objects.get(email=usr_email)
        except User.DoesNotExist:
            return Response({'error': 'User Not Found'}, status=404)

        if not todo.assigned_users.filter(username=user.username).exists():
            todo.assigned_users.add(user)

        return Response({'success': 'added user'}, status=200)

    if request.method == 'DELETE' and request.resolver_match.url_name == 'todo':

        if not todo_id:
            return Response({'error': 'Todo id is missing'}, status=400)

        try:
            todo = Todo.objects.get(id=todo_id)
        except Todo.DoesNotExist:
            return Response({'error': 'Not Found Todo'}, status=404)

        if todo.user != request.user:
            return Response({'error': 'Permission Denied'}, status=403)

        todo.delete()
        return Response({'success': 'todo is deleted'}, status=200)

    if request.method == 'DELETE' and request.resolver_match.url_name == 'users':

        if not todo_id:
            return Response({'error': 'Todo id is missing'}, status=400)

        try:
            todo = Todo.objects.get(id=todo_id)
        except Todo.DoesNotExist:
            return Response({'error': 'Not Found Todo'}, status=404)

        if todo.user != request.user:
            return Response({'error': 'Permission Denied'}, status=403)

        email = request.query_params.get('email', None)

        if not email:
            return Response({'error': 'Email is missing'}, status=400)

        try:
            user = User.objects.get(email=email)
        except User.DoesNotExist:
            return Response({'error': 'User not Found'}, status=404)

        if todo.assigned_users.filter(email=email).exists():
            todo.assigned_users.remove(user)
            return Response({'success': 'User removed the todo list'},
                            status=200)

        return Response({'error': 'Bad Request'}, status=400)
Пример #18
0
class TodoSerializer(serializers.ModelSerializer):
    id = serializers.ModelField(model_field=Todo()._meta.get_field('id'))

    class Meta:
        model = Todo
        fields = ('id', 'due_date', 'is_completed', 'label', 'list', 'title')
Пример #19
0
 def create(self, validated_data):
     todo = Todo(**validated_data)
     todo.save()
     return todo
Пример #20
0
 def create(self, validated_data):
     basket = validated_data.pop('basket', None)
     instance = Todo(**validated_data)
     instance.basket_id = basket.get('name')
     instance.save()
     return instance