查看待办事件列表
1. url 的配置
在main.py
代码中如下:
GET(SELECT):从服务器取出资源(一项或多项)。
import web
urls = (
'/', 'index',
'/TodoLists', 'todo.TD',
)
2. todo.TD
类增加GET方法
返回结果
GET /collection:返回资源对象的列表(数组)
在TD类添加Get方法如下:
class TD(object):
def GET(self):
web.header('Content-Type', 'application/json')
results = []
for post_data in collection.find().skip(0).limit(10):
post_data['_id'] = str(post_data['_id'])
post_data['post_date'] = post_data['post_date'].strftime('%Y-%m-%d %H:%M:%S')
results.append(post_data)
return json.dumps(results)
3. 分页请求
分页请求连接:http://192.168.17.129:8080/TodoLists?page=2&limit=10
class TD(object):
def GET(self):
i = web.input()
print i
page = int(i.get('page', 1))
limit = int(i.get('limit', 10))
skip_num = (page-1)*10
web.header('Content-Type', 'application/json')
results = []
for post_data in collection.find().skip(skip_num).limit(limit):
post_data['_id'] = str(post_data['_id'])
post_data['post_date'] = post_data['post_date'].strftime('%Y-%m-%d %H:%M:%S')
results.append(post_data)
return json.dumps(results)
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)