Flask REST API用JSONArray响应 [英] Flask REST API responding with a JSONArray

查看:128
本文介绍了Flask REST API用JSONArray响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Flask为Android应用程序创建了一个简单的REST API.我在实现GET方法时遇到了麻烦.应该以JSONArray的形式返回所有记录.响应看起来像他的

I have created a simple REST API using Flask for an Android application. I'm having trouble implementing the GET method. It is supposed to return all the records in the form of a JSONArray. The response would look something like his

{
    "tasks": [{
               "task" : "Do it",
               "timestamp": 1433510946152
              },{..}
             ],
    "success": 1
}

我的任务模型看起来像这样

My Task model looks like this

class Task(db.Model):   
    id = db.Column(db.Integer, primary_key=True)
    task= db.Column(db.Text, nullable=False)
    timestamp = db.Column(db.Integer, nullable=False)

    @staticmethod
    def newest():
        return Task.query.order_by(desc(Task.timestamp))

    def to_json(self):
        return dict(id=self.id,
                    task= self.task,
                    timestamp = self.timestamp)

to_json()方法将结果转换为JSON.我只是不知道如何正确使用它.我如何将所有记录放入JSONArray中?这是我获取所有任务的方法.我也使用Flask分页,所以任务是分页对象.

The to_json() method converts the result into JSON. I just don't know how to use it appropriately. How would I put all the records inside of an JSONArray? Here is my method that gets all the tasks. I'm using Flask paginate too, so tasks is a pagination object.

def get_tasks():    

    page = request.args.get('page')
    if page is not None:
        try:
            page = int(request.args.get('page'))
        except:
            return jsonify({'result': 'Invalid parameter'})
    else:
        page = 1
    tasks= models.Task.newest().paginate(page, 7, True)

    #How do I return the tasks in an appropriate format?

任何帮助将不胜感激.谢谢.

Any help would be appreciated. Thanks.

推荐答案

简单地循环遍历您的tasks,使用to_json将它们转换为json并将它们存储在数组中.例如:

Simply loop over your tasks, convert them into json using your to_json and store them inside of an array. For example:

def get_tasks():    

    page = request.args.get('page')
    if page is not None:
        try:
            page = int(request.args.get('page'))
        except:
            return jsonify({'result': 'Invalid parameter'})
    else:
        page = 1
    tasks= models.Task.newest().paginate(page, 7, True)
    # This list will hold all your tasks in JSON format
    jsontasks = []
    # Since tasks is a pagination object, you should use tasks.items
    for task in tasks.items:
        jsontasks.append(task.to_json())
    #How do I return the tasks in an appropriate format? Like this..
    return jsonify({'tasks': jsontasks, 'success': 1})

这篇关于Flask REST API用JSONArray响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆