flask-restful中,我创建了一个简单的get,它返回JSON中的记录列表。

resource_fields = {
            'record_date': fields.String,
            'rating': fields.Integer,
            'notes': fields.String,
            'last_updated': fields.DateTime,
        }

class Records(Resource):
def get(self, email, password, last_sync_date):
    user, em_login_provider = Rest_auth.authenticate(email, password)
    resource_fields = {
        'record_date': fields.String,
        'rating': fields.Integer,
        'notes': fields.String,
        'last_updated': fields.DateTime,
    }
    m_records = []
    if user:
        try:
            date = parser.parse(last_sync_date)
        except:
            #Never synced before - get all
            recordsdb = Record.query(Record.user == user.key)
            for record in recordsdb:
                m_record = marshal(record, resource_fields);
                m_records.append(m_record);
            return json.dumps(m_records)
    return {'data': 'none'}


现在在单元测试中,将接收到的字符串加载到json解析器中之后,我仍然得到一个unicode。

像这样:

[
    {
        "rating": 1,
        "notes": null,
        "last_updated": "Mon, 14 Oct 2013 20:56:09 -0000",
        "record_date": "2013-10-14"
    },
    {
        "rating": 2,
        "notes": null,
        "last_updated": "Mon, 14 Oct 2013 20:56:09 -0000",
        "record_date": "2013-09-14"
    }
]


单元测试:

rv = self.app.get('/rest/records/{0}/{1}/{2}'.format(email, password, sync_date))
resp = json.loads(rv.data)
eq_(len(resp),2)


但是因为它是一个带有200个字符的unicode,而不是一个包含两个对象的列表,所以单元测试失败。

知道我想念的是什么吗?

print repr(resp)输出以下内容:

str: u'[{"rating": 1, "notes": null, "last_updated": "Mon, 14 Oct 2013 21:33:07 -0000", "record_date": "2013-10-14"}, {"rating": 2, "notes": null, "last_updated": "Mon, 14 Oct 2013 21:33:07 -0000", "record_date": "2013-09-14"}]'


希望这可以帮助

最佳答案

Flask-restful已经为您将数据编码为JSON。您返回了JSON字符串,Flask再次将其编码为JSON。

而是返回一个列表:

return m_records

关于python - 为什么返回的JSON被理解为unicode而不是列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19368643/

10-17 02:19