示例#1
0
	def get(self, tid):
		''''''
		try:
			print tid
			TodoItem.objects(id=tid).delete()
		except Exception, e:
			return self.write(json.dumps({'stat':'error'}))
示例#2
0
 def mutate(self, name, todo_list_id):
     if request.method == "POST":
         todo_list = TodoListModel.query.get(todo_list_id)
         todo_item = TodoItemModel(name=name, todo_list=todo_list)
         todo_item.create()
         result = Success(yeah='yeah')
         return CreateTodoItem(result=result)
示例#3
0
 def post(self, **kwargs):
     data = super().post()
     todo_list = self.get_todo_list(**kwargs)
     new_todo_item = TodoItem(content=data.get('content'), todo_list=todo_list)
     self.session.add(new_todo_item)
     self.session.commit()
     return self.make_response(new_todo_item.serialize())
示例#4
0
def test_respect_order_by_id(items, chat):
    TodoItem.update(id=100500).where(TodoItem.id == items[0].id).execute()

    lines = chat.get_formatted_items().split("\n")

    assert len(lines) == 2
    assert "1. Nice!" == lines[0]
    assert "2. Hello" == lines[1]
示例#5
0
	def post(self, tid):
		''''''
		content = self.get_argument('content')
		try:
			print tid, content
			TodoItem.objects(id=tid).update_one(set__content=content)
		except Exception, e:
			return self.write(json.dumps({'stat':'error'}))
示例#6
0
    def delete(self):
        json_data = request.get_json(force=True)

        if not json_data['id']:
            return {'message': 'No id was provided'}, 400

        TodoItem.objects(id=json_data['id']).delete()

        return {"status": 'success'}, 204
示例#7
0
def todo_create():
    todo = request.get_json()
    new_todo = TodoItem(title = todo['title'],
            completed = todo['completed'],
            order = todo['order'],
            user_id = current_user.id)
    db.session.add(new_todo)
    db.session.commit()
    return jsonify(new_todo.serialize())
def test_create_and_get_item(app):
    text = 'Yoooloooo'
    item = TodoItem(text=text)
    item.save()
    item_fetched = TodoItem.select().where(
        TodoItem.id==item.id
    ).get()

    assert item.id is not None
    assert item.id == item_fetched.id
示例#9
0
def todo(request, project_name):
    """Allows to create a new todolist and todoitems.
    Actions available here:
    Add a todolist: Owner Participant
    Add a todoitem: Owner Participant
    """
    project = get_project(request, project_name)
    access = get_access(project, request.user)
    if request.GET.get('includecomplete', 0):
        lists = TodoList.objects.filter(user=request.user, project=project)
    else:
        lists = TodoList.objects.filter(user=request.user, project=project, is_complete_attr=False)
    addlistform = bforms.AddTodoListForm()
    if request.method == 'POST':
        if request.POST.has_key('addlist'):
            addlistform = bforms.AddTodoListForm(project, request.user, request.POST)
            if addlistform.is_valid():
                addlistform.save()
                return HttpResponseRedirect('.')
        elif request.POST.has_key('additem'):
            id = int(request.POST['id'])
            list = TodoList.objects.get(id=id)
            text_id = '%s-text' % list.id
            if request.POST[text_id]:
                item = TodoItem(list=list, text=request.POST[text_id])
                item.save()
        elif request.POST.has_key('listmarkdone'):
            id = int(request.POST['id'])
            list = TodoList.objects.get(id=id)
            list.is_complete = True
            list.save()
            return HttpResponseRedirect('.')
        elif request.POST.has_key('itemmarkdone'):
            id = int(request.POST['id'])
            todoitem = TodoItem.objects.get(id=id)
            todoitem.is_complete = True
            todoitem.save()
            return HttpResponseRedirect('.')

    if request.method == 'GET':
        addlistform = bforms.AddTodoListForm()

    if request.GET.get('csv', ''):
        response, writer = reponse_for_cvs(project=project)
        writer.writerow(('Todo Lists',))
        writer.writerow(TodoList.as_csv_header())
        lists = TodoList.objects.filter(user=request.user, project=project)
        for list in lists:
            writer.writerow(list.as_csv())
        for list in lists:
            for item in list.todoitem_set.all():
                writer.writerow(item.as_csv())
        return response
    payload = {'project': project, 'lists': lists, 'addlistform': addlistform}
    return render(request, 'project/todo.html', payload)
示例#10
0
文件: views.py 项目: sagittarian/todo
def additem(request, label, priority):
    '''Add the item specified in the POST request with the given label
    and optional priority.'''
    if label is None:
        return {'error': 'Must provide a label for a new item'}
    kw = {'label': label, 'user': request.user}
    if priority is not None:
        kw['priority'] = priority
    item = TodoItem(**kw)
    item.save()
    return {'id': item.pk}
示例#11
0
    def do(self):
        if not self.chat.enabled:
            return

        if self.chat.has_no_recent_activity:
            self.common_reply("to_check_off_help")

        for text in self.cleaned_lines():
            TodoItem.create(chat=self.chat, text=text)

        self.reply(self.chat.get_formatted_items())
示例#12
0
 def post(self, **kwargs):
     todo_list_id = kwargs.get('todo_list_id')
     data = request.data
     print(data)
     data = json.loads(data)
     content = data.get('content')
     if not content:
         return abort(400, 'no content posted')
     new_item = TodoItem(todo_list_id=todo_list_id, content=content)
     self.session.add(new_item)
     self.session.commit()
     return json.dumps(new_item.serialize())
示例#13
0
 def mutate(self, args, request, info):
     with make_session_scope() as sess:
         todo_item = TodoItem(**args, is_done=False)
         sess.add(todo_item)
         sess.commit()
         todo = sess.query(Todo).get(args.get('todo_id'))
         return AddTodoItem(ok=True, user=todo.user)
示例#14
0
 def post(self, account_id, todo_list_id, todo_item_id):
     self.response.headers['Content-Type'] = 'application/json'
     try:
         account = Account.get_by_id(int(account_id))
         todo_list = TodoList.get_by_id(id=int(todo_list_id), parent=account.key)
         item_data = json.loads(self.request.body)
         todo_iem = TodoItem.get_by_id(id=int(todo_item_id), parent=todo_list.key)
         if todo_iem:
             todo_iem.populate(**item_data)
             todo_iem.put()
             item_dict = todo_iem.to_dict(exclude=['created', 'updated', 'todo_list'])
             item_dict['id'] = todo_iem.key.id()
             self.response.out.write(json.dumps(item_dict))
         else:
             result = {'error': 'Bad Request', 'message': 'Invalid todo item %s' % todo_item_id}
             self.response.set_status(400, json.dumps(result))
             self.response.out.write(json.dumps(result))
     except AttributeError as ae:
         result = {'error': 'Bad request', 'message': ae.message}
         self.response.set_status(400, json.dumps(result))
         self.response.out.write(json.dumps(result))
     except Exception as e:
         result = {'error': 'Unexpected error has occurred', 'message': e.message}
         self.response.set_status(500, json.dumps(result))
         self.response.out.write(json.dumps(result))
示例#15
0
def todos_item(request, list_id, item_id):
    if request.method == 'OPTIONS':
        return HttpResponse()

    try:
        i = TodoItem.get(list_id, item_id)
    except TodoItem.DoesNotExist:
        return HttpResponseNotFound()

    if request.method == 'GET':
        return _item_response(i)
    elif request.method == 'PUT':
        params = json.loads(request.body)
        fields = []
        if 'text' in params:
            i.text = params['text']
            fields.append('text')
        if 'completed' in params:
            if not isinstance(params['completed'], bool):
                raise HttpResponseBadRequest()
            i.completed = params['completed']
            fields.append('completed')
        cursor = i.save(fields=fields)
        if cursor.cur != cursor.prev:
            _publish_item(list_id, i, cursor)
        return _item_response(i)
    elif request.method == 'DELETE':
        cursor = i.delete()
        if cursor.cur != cursor.prev:
            _publish_item(list_id, i, cursor)
        return HttpResponse(status=204)
    else:
        return HttpResponseNotAllowed(['GET', 'POST', 'DELETE'])
示例#16
0
  def post(self, my_list):
    if my_list.task_count >= 100:
      self.bad_request()
      return

    text = self.request.get('text')
    if not text:
      self.bad_request()
      return

    item = TodoItem(parent=my_list, text=text, completed=False)
    my_list.task_count += 1
    my_list.put()
    item.put()

    self.json({'item': item.to_dict()})
示例#17
0
def todos_item(request, list_id, item_id):
	if request.method == 'OPTIONS':
		return HttpResponse()

	try:
		i = TodoItem.get(list_id, item_id)
	except TodoItem.DoesNotExist:
		return HttpResponseNotFound()

	if request.method == 'GET':
		return _item_response(i)
	elif request.method == 'PUT':
		params = json.loads(request.body)
		fields = []
		if 'text' in params:
			i.text = params['text']
			fields.append('text')
		if 'completed' in params:
			if not isinstance(params['completed'], bool):
				raise HttpResponseBadRequest()
			i.completed = params['completed']
			fields.append('completed')
		cursor = i.save(fields=fields)
		if cursor.cur != cursor.prev:
			_publish_item(list_id, i, cursor)
		return _item_response(i)
	elif request.method == 'DELETE':
		cursor = i.delete()
		if cursor.cur != cursor.prev:
			_publish_item(list_id, i, cursor)
		return HttpResponse(status=204)
	else:
		return HttpResponseNotAllowed(['GET', 'POST', 'DELETE'])
示例#18
0
def get_todos(request):
    todos = TodoItem.objects
    if request.method == "GET":
        return HttpResponse(todos.to_json())
    elif request.method == "POST":
        item = TodoItem.from_json(request.body)
        item.save()
        return HttpResponse(todos.to_json())
示例#19
0
  def task_handler_method(self, my_list, task_id):
    task_id = long(task_id)
    task = TodoItem.get_by_id(task_id, parent=my_list)
    if not task:
      self.not_found()
      return

    return method(self, my_list, task)
示例#20
0
def new_todo():
    if request.method == 'POST':
        todo = TodoItem(name=request.form['name'],
                        deadline_date=datetime.datetime.strptime(
                            request.form['deadline_date'], "%m/%d/%Y").date(),
                        users_id=current_user.id)
        db.session.add(todo)
        db.session.commit()
        return redirect(url_for('success'))
    return render_template('new-todo.html', page='new-todo')
示例#21
0
 def post(self, account_id, todo_list_id):
     self.response.headers['Content-Type'] = 'application/json'
     try:
         data = json.loads(self.request.body)
         items = data.get('items', [data])
         account = Account.get_by_id(int(account_id))
         todo_list = TodoList.get_by_id(id=int(todo_list_id), parent=account.key)
         item_array = []
         for item_data in items:
             item = TodoItem(text=item_data.get('text'), status=item_data.get('status'), todo_list=todo_list.key,
                             parent=todo_list.key)
             item.put()
             item_array.append({'id': item.key.id()})
         result = {'items': item_array}
         self.response.out.write(json.dumps(result))
     except Exception as e:
         result = {'error': 'Unexpected error has occurred', 'message': e.message}
         self.response.set_status(500, json.dumps(result))
         self.response.out.write(json.dumps(result))
示例#22
0
def addItem(listid, item):
    if listid is None or item is None:
        return abort()
    list = TodoList.query.filter_by(id=listid).first()
    if list is None:
        return abort()
    newItem = TodoItem(list=list, description=item)
    db.session.add(newItem)
    db.session.commit()
    return redirect(url_for("routes.viewList", listid = listid))
示例#23
0
    def post(self):
        # validate incoming data
        parser.add_argument('title', type=str, required=True)
        parser.add_argument('description', type=str)

        # parse args
        args = parser.parse_args()
        title = args['title']
        description = args['description']
        
        # create new todo
        new_todo = TodoItem(title, description)
        print(new_todo)

        # save todo
        Todos.append(new_todo)

        # return8888 created todo
        return new_todo.serialize(), 201
示例#24
0
文件: app.py 项目: mehranj73/Bootcamp
def create_dummy_data():
    for i in range(10):
        new_list = TodoList(name=randomword(10))
        for i2 in range(10):
            new_item = TodoItem(
                content=randomword(100),
                todo_list=new_list,
            )
            db.session.add(new_item)
    db.session.commit()
    print('Created 10 Todo lists with each' ' 10 items!')
示例#25
0
def todos(request, list_id):
	if request.method == 'OPTIONS':
		resp = HttpResponse()
		resp['Access-Control-Max-Age'] = '3600'
		return resp

	if request.method == 'HEAD':
		last_cursor = TodoItem.get_last_cursor(list_id)
		resp = HttpResponse()
		resp['Link'] = _changes_link(list_id, last_cursor.cur)
		return resp
	elif request.method == 'GET':
		stream = request.GET.get('stream')
		after = request.GET.get('after_change')
		wait = request.META.get('HTTP_WAIT')
		if stream:
			stream = (stream == 'true')
		if wait:
			wait = int(wait)

		if stream:
			set_hold_stream(request, Channel('todos-%s' % list_id))
			return HttpResponse(content_type='text/plain')
		else:
			if after:
				try:
					items, last_cursor = TodoItem.get_after(list_id, after)
				except TodoItem.DoesNotExist:
					return HttpResponseNotFound()
			else:
				items, last_cursor = TodoItem.get_all(list_id)
			resp = _list_response(list_id, items)
			resp['Link'] = _changes_link(list_id, last_cursor.cur)
			if len(items) == 0 and wait:
				set_hold_longpoll(request, Channel('todos-%s' % list_id, prev_id=last_cursor.cur), timeout=wait)
			return resp
	elif request.method == 'POST':
		params = json.loads(request.body)
		i = TodoItem(list_id=list_id)
		if 'text' in params:
			i.text = params['text']
		if 'completed' in params:
			if not isinstance(params['completed'], bool):
				return HttpResponseBadRequest('completed must be a bool\n', content_type='text/plain')
			i.completed = params['completed']
		try:
			cursor = i.save()
		except TodoItem.LimitError:
			return HttpResponseForbidden('limit reached\n', content_type='text/plain')
		if cursor.cur != cursor.prev:
			_publish_item(list_id, i, cursor)
		resp = _item_response(i, status=201)
		resp['Location'] = reverse('todos-item', args=[list_id, i.id])
		return resp
	else:
		return HttpResponseNotAllowed(['HEAD', 'GET', 'POST'])
示例#26
0
 def get(self, account_id, todo_list_id, todo_item_id):
     self.response.headers['Content-Type'] = 'application/json'
     try:
         account = Account.get_by_id(int(account_id))
         todo_list = TodoList.get_by_id(id=int(todo_list_id), parent=account.key)
         todo_item = TodoItem.get_by_id(id=int(todo_item_id), parent=todo_list.key)
         todo_item_dict = todo_item.to_dict(exclude=['todo_list', 'created', 'updated'])
         self.response.out.write(json.dumps(todo_item_dict))
     except Exception as e:
         result = {'error': 'Unexpected error has occurred', 'message': e.message}
         self.response.set_status(500, json.dumps(result))
         self.response.out.write(json.dumps(result))
示例#27
0
    def post(self):
        json_data = request.get_json(force=True)

        if not json_data:
            return {'message': 'No valid data provided'}, 400

        # Deserialize input
        data, errors = todo_item_schema.load(json_data)
        if errors:
            return errors, 422

        todo_item = TodoItem.objects(title=data['title']).first()
        if todo_item:
            return {
                'message': 'A todo item with the same title already exists'
            }, 400

        todo_item = TodoItem(title=json_data['title'])
        todo_item.save()

        # Serialize and dump input
        result = todo_item_schema.dump(todo_item).data

        return {"status": 'success', 'data': result}, 201
示例#28
0
 def get(self, account_id, todo_list_id):
     self.response.headers['Content-Type'] = 'application/json'
     try:
         account = Account.get_by_id(int(account_id))
         todo_list = TodoList.get_by_id(id=int(todo_list_id), parent=account.key)
         todo_items = TodoItem.query(TodoItem.todo_list == todo_list.key,
                                     ancestor=todo_list.key).order(-TodoItem.created)
         todo_items_array = []
         for item in todo_items:
             item_dict = item.to_dict(exclude=['created', 'updated', 'todo_list'])
             item_dict['id'] = item.key.id()
             todo_items_array.append(item_dict)
         result = {'todo_items': todo_items_array}
         self.response.out.write(json.dumps(result))
     except Exception as e:
         result = {'error': 'Unexpected error has occurred', 'message': e.message}
         self.response.set_status(500, json.dumps(result))
         self.response.out.write(json.dumps(result))
示例#29
0
    def put(self):
        json_data = request.get_json(force=True)
        if not json_data:
            return {'message': 'No valid data provided'}, 400

        print(json_data)
        data, errors = todo_item_schema.load(json_data)

        if errors:
            return errors, 422

        todo_item = TodoItem.objects(id=data['id']).first()

        if not todo_item:
            return {'message': 'Todo item does not exist'}, 400

        todo_item.update(**json_data)
        todo_item.save()

        result = todo_item_schema.dump(todo_item).data

        return {"status": 'success', 'data': result}, 204
示例#30
0
 def render_todo(self):
     items = TodoItem.select()
     return render_template('todo.html', items=items)
示例#31
0
async def create_todo(todo: TodoItem):
    item = todo.dict()
    item['id'] = len(TODOS) + 1
    return item
def test_do_not_drop_other_chat_items_after_start(action, factory):
    factory.item()

    action.do()

    assert TodoItem.select().count() == 1
示例#33
0
def _add_totals(list_id, data):
	total, completed = TodoItem.get_totals(list_id)
	data['total-items'] = total
	data['total-completed'] = completed
def test_drop_items_after_start(action, factory, chat):
    factory.item(chat=chat)

    action.do()

    assert TodoItem.select().count() == 0
示例#35
0
from models import TodoItem

TodoItem(title="Do laundry").save()
TodoItem(title="Buy groceries").save()
TodoItem(title="Hit the gym").save()
TodoItem(title="Read 20 pages of book X").save()
TodoItem(title="Call friend").save()
TodoItem(title="Go to bank").save()
TodoItem(title="Meditate for 5 min").save()
TodoItem(title="Learn flask framework").save()


示例#36
0
 def item(self, **kwargs):
     chat = kwargs.pop("chat", None) or self.chat()
     text = kwargs.pop("text", "some")
     return TodoItem.create(chat=chat, text=text, **kwargs)
示例#37
0
def todos(request, list_id):
    if request.method == 'OPTIONS':
        resp = HttpResponse()
        resp['Access-Control-Max-Age'] = '3600'
        return resp

    if request.method == 'HEAD':
        last_cursor = TodoItem.get_last_cursor(list_id)
        resp = HttpResponse()
        resp['Link'] = _changes_link(list_id, last_cursor.cur)
        return resp
    elif request.method == 'GET':
        stream = request.GET.get('stream')
        after = request.GET.get('after_change')
        wait = request.META.get('HTTP_WAIT')
        if stream:
            stream = (stream == 'true')
        if wait:
            wait = int(wait)

        if stream:
            set_hold_stream(request, Channel('todos-%s' % list_id))
            return HttpResponse(content_type='text/plain')
        else:
            if after:
                try:
                    items, last_cursor = TodoItem.get_after(list_id, after)
                except TodoItem.DoesNotExist:
                    return HttpResponseNotFound()
            else:
                items, last_cursor = TodoItem.get_all(list_id)
            resp = _list_response(list_id, items)
            resp['Link'] = _changes_link(list_id, last_cursor.cur)
            if len(items) == 0 and wait:
                set_hold_longpoll(request,
                                  Channel('todos-%s' % list_id,
                                          prev_id=last_cursor.cur),
                                  timeout=wait)
            return resp
    elif request.method == 'POST':
        params = json.loads(request.body)
        i = TodoItem(list_id=list_id)
        if 'text' in params:
            i.text = params['text']
        if 'completed' in params:
            if not isinstance(params['completed'], bool):
                return HttpResponseBadRequest('completed must be a bool\n',
                                              content_type='text/plain')
            i.completed = params['completed']
        try:
            cursor = i.save()
        except TodoItem.LimitError:
            return HttpResponseForbidden('limit reached\n',
                                         content_type='text/plain')
        if cursor.cur != cursor.prev:
            _publish_item(list_id, i, cursor)
        resp = _item_response(i, status=201)
        resp['Location'] = reverse('todos-item', args=[list_id, i.id])
        return resp
    else:
        return HttpResponseNotAllowed(['HEAD', 'GET', 'POST'])
示例#38
0
 def post(self):
     text = request.form.get('text')
     item = TodoItem(text=text)
     item.save()
     return self.render_todo()
示例#39
0
def _add_totals(list_id, data):
    total, completed = TodoItem.get_totals(list_id)
    data['total-items'] = total
    data['total-completed'] = completed
示例#40
0
 def post(self, tid):
     task = request.form['task'].strip()
     todo = TodoItem.create(tid, task, current_user)
     db.session.add(todo)
     db.session.commit()
     return todo.to_dict()