Preprocess function Flask Restless

1.1k views Asked by At

I'm trying to combine Ember.js and Flask Restless, but am running into difficulties interfacing the JSON API.

The problem is that I need to massage the JSON to match what Ember is expecting client side.

Ember is sending something like this on POST:

u'todo': {u'isCompleted': False, u'title': u'hello'}}

but Flask Restless expects something like this

{'is_completed': False, 'title': u'hello'}

I am able to do this as can be seen below, but since the Flask Restless preproccesor doesn't accept a return argument, and data object must be changed in place and creating a new dict containing what I want won't work. So I need to clumsily alter the given data dict by adding and removing the keys that I need.

Does anyone have a better solution that scales easily to more complicated models?

def ember_formatter(result):
    for key in result.keys():
        if key != 'objects':
            del result[key]

    result['todos'] = result['objects']
    del result['objects']

def pre_ember_formatter(data=None, **kw):

    data['is_completed'] = data['todo']['isCompleted']
    data['title'] = data['todo']['title']
    del data['todo']

restless_manager.create_api(
    Todo,
    methods=['GET', 'POST', 'DELETE', 'PUT', 'PATCH'],
    url_prefix='/api',
    collection_name='todos',
    results_per_page=-1,
    postprocessors={
        'GET_MANY': [ember_formatter]
    },
    preprocessors={
        'POST': [pre_ember_formatter],
    }
)
2

There are 2 answers

0
Toran Billups On BEST ANSWER

I'm not 100% sure how close the restless api maps to the django-rest-framework, but in your example above the DRF adapter will work out of the box.

https://github.com/toranb/ember-data-django-rest-adapter

With this approach you could leave your JSON api as is and just plug in a new client side adapter

0
dvreed77 On

I'll give this to Toran cause his method eventually led to the path on enlightenment, but wanted to be explicit about how I was able to do this.

I found that it was actually easier to make all these changes on the client side, in Ember. The general idea is that you need to alter the JSON coming in from the server, and alter the JSON leaving the client.

This is all done in the DS.RESTSerializer class, and if you look, there examples on how to do this, Ember's documentation is awesome once you get used to it.

So, to modify JSON coming in from the server, you want to modify the extractArray and extractSingle function.

To modify the JSON leaving the client, you want to modify the serialize and serializeIntoHash functions, its really simple.

I think it makes sense to do this all in Ember, because you usually don't have control over the API your talking to.