add basic validation support
This commit is contained in:
+11
-2
@@ -2,6 +2,7 @@ from flask import Flask, jsonify, Response, request
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from api.extensions.esales import Esales
|
||||
from api.helpers import check_api_key
|
||||
from api.validators import ValidationError
|
||||
|
||||
db = SQLAlchemy()
|
||||
esales = Esales()
|
||||
@@ -15,8 +16,16 @@ def create_app(config_name='config'):
|
||||
|
||||
# register errors handlers
|
||||
@app.errorhandler(404)
|
||||
def on_404(e):
|
||||
return jsonify(dict(error='Not found')), 404
|
||||
def on_404(error):
|
||||
response = jsonify({'status': 404, 'message': 'The requested resource was not found'})
|
||||
response.status_code = 404
|
||||
return response
|
||||
|
||||
@app.errorhandler(ValidationError)
|
||||
def on_validation_error(error):
|
||||
response = jsonify({'status': 400, 'message': error.message})
|
||||
response.status_code = 400
|
||||
return response
|
||||
|
||||
# register blueprints
|
||||
from api.views import server, designers, categories
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# coding=UTF-8
|
||||
|
||||
class ValidationError(Exception):
|
||||
|
||||
def __init__(self, message):
|
||||
Exception.__init__(self)
|
||||
self.message = message
|
||||
|
||||
|
||||
def validate_keys_exists(obj, *keys):
|
||||
for key in keys:
|
||||
if not key in obj:
|
||||
raise ValidationError('No {} is specified'.format(key))
|
||||
return True
|
||||
@@ -1,6 +1,8 @@
|
||||
from flask import Blueprint, request, jsonify
|
||||
from api import db, tasks
|
||||
from api.models import Designer
|
||||
from api.validators import validate_keys_exists
|
||||
|
||||
|
||||
mod = Blueprint('designers', __name__, url_prefix='/designers')
|
||||
|
||||
@@ -14,6 +16,7 @@ def list():
|
||||
@mod.route("/", methods=["POST"])
|
||||
def create():
|
||||
data = request.json
|
||||
validate_keys_exists(data, 'username', 'name')
|
||||
designer = Designer(**data)
|
||||
db.session.add(designer)
|
||||
db.session.commit()
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
import unittest2
|
||||
from api.validators import ValidationError, validate_keys_exists
|
||||
|
||||
|
||||
class TestValidation(unittest2.TestCase):
|
||||
|
||||
def test_validate_keys_exists(self):
|
||||
obj = {'a':1, 'b':2}
|
||||
self.assertRaises(ValidationError, validate_keys_exists, obj, 'c')
|
||||
self.assertRaises(ValidationError, validate_keys_exists, obj, 'a', 'b', 'c')
|
||||
self.assertTrue(validate_keys_exists(obj, 'a'))
|
||||
self.assertTrue(validate_keys_exists(obj, 'a', 'b'))
|
||||
Reference in New Issue
Block a user