Reputation: 2967
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?
Upvotes: 0
Views: 660
Reputation: 1121524
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.
Upvotes: 3