如何在python烧瓶中设置JSON返回时间

时间:2014-12-27 21:08:37

标签: python json flask sqlalchemy

在我的烧瓶应用中,前端和后端是分开的。如何在我设置的特定时间每天将JSON返回到前端。

例如

@api.route('/sda')
def Daily():
    # Get all entries (all students from all courses) that match today's date in MMDDYYYY format
    entries = Entry.query.filter_by(timestamp.strftime('%M%D%Y')=datetime.datetime.now().strftime('%M%D%Y')).all()
    # Count how many students attend school today (Since in the entries array, there are duplicate student with same ID, and I only want to count it once per student)
    # When the loop ends, it will return a jsonify with today's date and total number of students attend school today

JSON文件中的预期数据:

{
  "dsa": [
    {
      "date": "12252014", 
      "present": 470,
      "absent": 30
    }, 
    {
      "date": "12262014", 
      "present": 490,
      "absent": 10
    }, 
    {
      "date": "12272014", 
      "present": 400,
      "absent": 100
    }
}

由于我意识到每当前端访问路由/sda时,该函数每次都会返回jsonify,并在JSON文件中复制具有相同date的值。

1 个答案:

答案 0 :(得分:0)

如果我理解你的要求,那么最好的做法就是做这样的事情。

创建一个字典,并添加一个带有空列表的项目(dsa)作为值

myDict = {'dsa':[]}

然后在此列表中添加后续词典

myDict['dsa'].append({"date":myDate, "present":present,"absent":absent})

然后返回json.dumps(myDict)