2013-10-14 50 views
2

flask-restful我创建了一个简单的get,它返回JSON中的记录列表。为什么返回的JSON理解为unicode而不是列表?

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

希望这有助于

+1

*但由于其与200上下的人物,而不是一个有两个对象列表中的Unicode,单元测试失败*。你能告诉我们什么'印刷repr(resp)'是?这听起来不正确;你的方法应该返回一个表示列表的JSON字符串。 –

+0

当然,我刚刚添加它。谢谢 – Houman

+1

这不是我要求你提供的,那是你的测试失败; 'print repr(resp)'打印什么? –

回答

3

瓶,宁静已经您的数据进行编码以JSON你。您返回了一个JSON字符串,并且Flask再次将其编码为JSON

返回一个列表,而不是:

return m_records 
+0

测试通行证。非常感谢你。 :) – Houman

相关问题