2013-10-14 54 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

相關問題