Вопрос

Flask-Restless only accepts arguments that are columns defined in a SQLAlchemy model. I want to take something like blue green and store it in two columns primary_color and secondary_color.

Right now, I am POSTing the data as primary_color (an allowed field) and using a postprocessor to split it into primary_color and secondary_color.

Is it possible to do something cleaner and more semantic, like POST a colors field and then process it afterwards?

Это было полезно?

Решение

Request preprocessors are run before validating the POST data against the model.

Set a preprocessor on the API for POST requests that parses any colors key, altering the data dictionary in-place:

def preprocess_colors(data):
    colors = data.pop('colors', None)
    if colors is not None:
        # set primary and secondary colors
        data['primary_color'] = get_primary_color(color)
        data['secondary_color'] = get_secondary_color(colors)

You do need to remove the colors key from the dictionary to prevent Flask-Restless from complaining about the key being there.

A postprocessor could never have worked here; these are only called to alter the returned response after the new instance has been created already.

Alternatively, create a SQLAlchemy hybrid attribute on your model named colors that translates colors into primary and secondary colors in a setter.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top