如何返回“已经存在”?烧瓶不安的错误? [英] How to return "already exists" error in Flask-restless?
问题描述
我想做一些异常处理程序。我在python中结合使用Flask-restless和SQLAlchemy。
I would like to do some handler for exception. I'm using a combination of Flask-restless and SQLAlchemy in python.
我的问题:
当我使用数据库中已经存在的对象向api发送请求时,SQLAlchemy显示异常:
When I send request to api with object that already exists in DB, SQLAlchemy shows exception:
IntegrityError: (IntegrityError) column <column_name> is not unique u'INSERT INTO ...
所以我尝试添加属性 validation_exceptions
转换为 create_api
方法:
So I have tried to add attribute validation_exceptions
into create_api
method:
manager.create_api( ... , validation_exceptions=[IntegrityError])
但是响应json包含:
But response json contains:
{
"validation_errors": "Could not determine specific validation errors"
}
并且服务器api显示异常:
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 than 1 value to unpack
Flask-restless中的异常验证不适用于这种类型的异常(IntegrityError)
Exception validation in Flask-restless doesn't work with this type of exception (IntegrityError)
我该怎么办?可以为异常创建一些处理程序,并在json中返回我自己的错误消息吗?
What should I do? Is it possible to create some handler for exception and to return my own error message in json?
推荐答案
文档(迄今为止,该版本为v0.17.0)指出:
The documentation (v0.17.0 to date of this posting) states:
当前,Flask-Restless期望指定验证错误的实例具有errors属性,该属性是将字段名称映射为error的字典。描述(注:每个字段一个错误)。
Currently, Flask-Restless expects that an instance of a specified validation error will have a errors attribute, which is a dictionary mapping field name to error description (note: one error per field).
因此要更改 validation_errors $ c的内容$ c>您的异常需要一个包含字典的
错误
属性。该词典的内容将在服务器响应中显示为 validation_errors
。
So to change the content of validation_errors
your exception needs an errors
attribute that contains a dictionary. The content of this dictionary will appear in the servers response as validation_errors
.
来自 flask-restless / tests / test_validation.py :
class TestSimpleValidation(ManagerTestBase):
"""Tests for validation errors raised by the SQLAlchemy's simple built-in
validation.
For more information about this functionality, see the documentation for
:func:`sqlalchemy.orm.validates`.
"""
def setup(self):
"""Create APIs for the 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 be between 0 and 150')
raise exception
return number
@validates('articles')
def validate_articles(self, key, article):
if article.title is not None and 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])
请求:
data = dict(data=dict(type='person', age=-1))
response = self.app.post('/api/person', data=dumps(data))
响应:
HTTP/1.1 400 Bad Request
{ "validation_errors":
{
"age": "Must be between 0 and 150",
}
}
这篇关于如何返回“已经存在”?烧瓶不安的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!