# -*- coding: utf-8 -*-
from __future__ import absolute_import
from flask import request
from comm.db import db
from .comm.errno import E_SUCCESS, E_MISS_PARAM, E_WATCH_NOTEXIST, E_ILLEGAL_PARAMETER
from .comm.wrappers import Resource, api
import time
import datetime
era = datetime.datetime(1970, 1, 1)
def format_aggregate_result_date(data):
num = len(data)
if num == 4:
return '%04d-%02d-%02d %02d' % (data['y'], data['m'], data['d'], data['h'])
elif num == 3:
return '%04d-%02d-%02d' % (data['y'], data['m'], data['d'])
elif num == 2:
return '%04d-%02d' % (data['y'], data['m'])
else:
return str(data['y'])
class SportDataView(Resource):
def get(self, watch_id):
sport_type = {1: '跑步', 2: '晨练', 3: '登山', 4: '游泳'}
watch = db.watch.find({'$id': watch_id})
result = {}
cursor = None
start = float(request.data['start_time'])
end = float(request.data['end_time'])
query = {'watch_id': watch_id, 'type': int(request.data['sport_type'])}
if (end - start) < 86450:
# 按日统计
date_group_mode = {'y': {'$year': '$time'}, 'm': {'$month': '$time'}, 'd': {'$dayOfMonth': '$time'},
'h': {'$hour': '$time'}}
elif (end - start) < 604850:
# 按周统计
date_group_mode = {'y': {'$year': '$time'}, 'm': {'$month': '$time'}, 'd': {'$dayOfMonth': '$time'}}
elif (end - start) > 604850:
# 大于七天则按月统计
date_group_mode = {'y': {'$year': '$time'}, 'm': {'$month': '$time'}}
else:
return {'code': E_ILLEGAL_PARAMETER, 'msg': 'date mode is bad value'}
s = time.localtime(start)
e = time.localtime(end)
if watch:
try:
# 用于查询exerciselog表
query_ex = {'watch_id': watch_id, 'type': int(request.data['sport_type'])}
start = time.strftime('%Y-%m-%d', s)
end = time.strftime('%Y-%m-%d', e)
query_ex['date'] = {'$gte': start, '$lte': end}
# 用于查询step表
query['maketime'] = {'$gte': float(request.data['start_time']), '$lte': float(request.data['end_time'])}
if sport_type.has_key(int(request.data['sport_type'])):
if int(request.data['sport_type']) == 2 or int(request.data['sport_type']) == 4:
cursor = db.exercise_log.aggregate([
{'$match': query_ex},
{'$project': {
'time': {'$add': [{'$multiply': [1000, {'$add': ['$maketime', 28800]}]}, era]},
'n': '$long',
'c': '$calorie'
}},
{'$group': {
'_id': date_group_mode,
'n': {'$sum': '$n'},
'c': {'$sum': '$c'}
}}
])
# {'_id', 'watch_id', 'date', 'time', 'type', 'long'}
elif int(request.data['sport_type']) == 1 or int(request.data['sport_type']) == 3:
# {'_id', 'watch_id', 'maketime', 'step', 'duration', 'calorie', 'type'}
print query
cursor = db.step.aggregate([
{'$match': query},
{'$project': {
'time': {'$add': [{'$multiply': [1000, {'$add': ['$maketime', 28800]}]}, era]},
'n': '$step',
'c': '$calorie'
}},
{'$group': {
'_id': date_group_mode,
'n': {'$sum': '$n'},
'c': {'$sum': '$c'}
}}
])
duration = db.exercise_log.aggregate([
{'$match': query_ex},
{'$project': {
'id': '$watch_id',
'l': '$long',
}},
{'$group': {
'_id': '$id',
'l': {'$sum': '$l'},
}}
])
else:
raise ValueError
except ValueError, e:
return {
'code': E_MISS_PARAM,
'mag': e.message
}
result.setdefault('data', [])
ca = 0
du = 0
for i in cursor:
ca += i.get('c', 0)
for d in duration:
du += d.get('l', 0)
i['date'] = format_aggregate_result_date(i['_id'])
i['step'] = i['n']
del i['_id'], i['n']
result['data'].append(i)
result['duration'] = du
result['calorie'] = ca
result['num'] = db.exercise_log.count(query_ex)
return {
'code': E_SUCCESS,
'request': result
}
else:
return{
'code': E_WATCH_NOTEXIST,
'msg': 'There is no watch exist!'
}
def __mount__():
api.add_resource(SportDataView,'/watch//all/view/')