删除待办事件
1. url 的配置
在main.py
代码中:
urls = (
'/', 'index',
'/TodoLists', 'todo.TD',
'/TodoLists/(\w+)', 'todo.TD_Simple',
)
不用修改urls配置,为todo.TD_Simple
增加delete方法
2. 为todo.TD_Simple
类增加delete方法
DELETE /zoos/ID:删除某个动物园
服务器返回结果:
DELETE /collection/resource:返回一个空文档
class TD_Simple: #针对单个待办事件处理类
def DELETE(self, id):
'''
按ID删除结果
:param id:
:return:
'''
web.header('Content-Type', 'application/json')
if len(id)!=24:
return json.dumps({'error':'id length is error'})
todo = get_by_id(id)
if not todo:
return json.dumps({'error':'没找到这条记录'})
collection.remove({'_id':ObjectId(id)})
return json.dumps({})
3. postman 按id 删除一条数据
4. 完整代码
todo.py
完整代码如下:
# coding: utf-8
import web
import json
import datetime
from datetime import *
from main import collection
from bson.objectid import ObjectId
def formatField(data):
'''
格式化字段
:param data:
:return:
'''
data['_id'] = str(data['_id'])
data['post_date'] = data['post_date'].strftime('%Y-%m-%d %H:%M:%S')
return data
class TD(object): #针对待办事件列表 处理类
def POST(self):
'''
新建待办事件
:return:
'''
i = web.input()
print i
title = i.get('title', None)
if not title:
return json.dumps({'error':'标题让你吃了吗?'})
post_data={
'title':title,
'post_date':datetime.now()
}
collection.insert_one(post_data)
format_data = formatField(post_data)
web.header('Content-Type', 'application/json')
return json.dumps(format_data)
def GET(self):
'''
查看待办事件
:return:
'''
i = web.input()
print i
page = int(i.get('page', 1))
limit = int(i.get('limit', 10))
skip_num = (page-1)*10
results = []
for post_data in collection.find().skip(skip_num).limit(limit):
format_data = formatField(post_data)
results.append(format_data)
web.header('Content-Type', 'application/json')
return json.dumps(results)
def get_by_id(id):
'''
按ID查询数据库
:param id:
:return:
'''
if len(id) != 24:
return False
s = collection.find_one({'_id':ObjectId(id)})
if not s:
return False
return s
class TD_Simple: #针对单个待办事件处理类
def GET(self, id):
'''
按ID查询返回结果
:param id:
:return:
'''
web.header('Content-Type', 'application/json')
todo = get_by_id(id)
if not todo:
return json.dumps({'error':'没找到这条记录'})
format_data = formatField(todo)
return json.dumps(format_data)
def PATCH(self, id):
'''
按ID查询修改结果
:param id:
:return:
'''
todo = get_by_id(id)
web.header('Content-Type', 'application/json')
if not todo:
return json.dumps({'error':'没找到这条记录'})
i = web.input()
print i
title = i.get('title', None)
if not title:
return json.dumps({'error':'标题让你吃了吗?'})
collection.update({'_id':ObjectId(id)}, {"$set":{'title': title}})
#修改成功
todo = get_by_id(id)
format_data = formatField(todo)
return json.dumps(format_data)
def DELETE(self, id):
'''
按ID删除结果
:param id:
:return:
'''
web.header('Content-Type', 'application/json')
todo = get_by_id(id)
if not todo:
return json.dumps({'error':'没找到这条记录'})
collection.remove({'_id':ObjectId(id)})
return json.dumps({})