python - How to return "already exists" error in Flask-restless? -
i handler exception. i'm using combination of flask-restless , sqlalchemy in python.
my problem:
when send request api object exists in db, sqlalchemy shows exception:
integrityerror: (integrityerror) column <column_name> not unique u'insert ...
so have tried add attribute validation_exceptions
create_api
method:
manager.create_api( ... , validation_exceptions=[integrityerror])
but response json contains:
{ "validation_errors": "could not determine specific validation errors" }
and server api shows exception :
traceback (most recent call last): file "c:\python27\lib\site-packages\flask_restless\views.py", line 797, in _extract_error_messages left, right = str(exception).rsplit(':', 1) valueerror: need more 1 value unpack
exception validation in flask-restless doesn't work type of exception (integrityerror)
what should do? possible create handler exception , return own error message in json?
the documentation (v0.17.0 date of posting) states:
currently, flask-restless expects instance of specified validation error have errors attribute, dictionary mapping field name error description (note: 1 error per field).
so change content of validation_errors
exception needs errors
attribute contains dictionary. content of dictionary appear in servers response validation_errors
.
from flask-restless/tests/test_validation.py:
class testsimplevalidation(managertestbase): """tests validation errors raised sqlalchemy's simple built-in validation. more information functionality, see documentation :func:`sqlalchemy.orm.validates`. """ def setup(self): """create apis validated models.""" super(testsimplevalidation, self).setup() class person(self.base): __tablename__ = 'person' id = column(integer, primary_key=true) age = column(integer, nullable=false) @validates('age') def validate_age(self, key, number): if not 0 <= number <= 150: exception = coolvalidationerror() exception.errors = dict(age='must between 0 , 150') raise exception return number @validates('articles') def validate_articles(self, key, article): if article.title not none , len(article.title) == 0: exception = coolvalidationerror() exception.errors = {'articles': 'empty title not allowed'} raise exception return article class article(self.base): __tablename__ = 'article' id = column(integer, primary_key=true) title = column(unicode) author_id = column(integer, foreignkey('person.id')) author = relationship('person', backref=backref('articles')) self.article = article self.person = person self.base.metadata.create_all() self.manager.create_api(article) self.manager.create_api(person, methods=['post', 'patch'], validation_exceptions=[coolvalidationerror])
request:
data = dict(data=dict(type='person', age=-1)) response = self.app.post('/api/person', data=dumps(data))
response:
http/1.1 400 bad request { "validation_errors": { "age": "must between 0 , 150", } }