【问题标题】:Why is the returned JSON understood as unicode instead of a list?为什么返回的 JSON 被理解为 unicode 而不是列表?
【发布时间】:2013-10-22 12:21:27
【问题描述】:

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"}]'

希望对你有帮助

【问题讨论】:

  • 但是因为它是一个包含 200 个字符的 unicode,而不是一个包含两个对象的列表,所以单元测试失败了。你能告诉我们print repr(resp) 是什么吗?这听起来不正确;您的方法应该返回一个表示列表的 JSON 字符串。
  • 当然,我刚刚添加了它。谢谢
  • 这不是我要求你提供的,那是你的测试失败; print repr(resp) 打印什么?
  • 另外,您是发布整个视图代码还是仅发布您认为运行的部分?你能展示带有方法签名的完整视图代码吗?
  • 好的,我已将两个请求更新到问题中。

标签: python json flask flask-restful


【解决方案1】:

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

返回一个列表:

return m_records

【讨论】:

  • 测试通过。非常感谢。 :)
猜你喜欢
  • 1970-01-01
  • 2011-11-10
  • 2016-10-15
  • 1970-01-01
  • 2014-11-15
  • 1970-01-01
相关资源
最近更新 更多