-
-
Save vtemian/8bd9176bc05c2fccaea2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from functools import wraps | |
from flask import request | |
from utils.exceptions import HttpNotFound | |
from utils.validators import Required | |
def require(f): | |
@wraps(f) | |
def decorated(view): | |
if request.method not in ['POST', 'PUT'] or not request.data: | |
return f(view) | |
required_payload = [] | |
for key in view.model.__dict__: | |
if key.startswith('validate_'): | |
validators = view.model.__dict__[key].validators | |
if any([isinstance(validator, Required) | |
for validator in validators]): | |
required_payload.append(key[9:]) | |
data = json.loads(request.data) | |
fields = set(required_payload) - set(data.keys()) | |
if fields != set([]): | |
raise HttpNotFound({ | |
'error': 'Field %s was not found in payload' % "".join(fields) | |
}) | |
request.data = json.dumps({ | |
column: data[column] for column in view.model.columns | |
}) | |
return f(view) | |
return decorated |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment