Question

In flask-restful I have created a simple get that returns a list of records in 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'}

Now in the unit test, after loading the received string into json parser, I still get a unicode.

Like this:

[
    {
        "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"
    }
]

Unit Test:

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

But because its a unicode with 200-ish characters and not a list with two objects, the unit test fails.

Any idea what I am missing please?

print repr(resp) outputs this:

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

Hope this helps

Was it helpful?

Solution

Flask-restful is already encoding your data to JSON for you. You returned a JSON string, and Flask encoded it to JSON again.

Return a list instead:

return m_records
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top