Mep*_*ph- 6 python validation exception-handling flask-sqlalchemy flask-restless
我想为异常做一些处理程序.我在python中使用了Flask-restless和SQLAlchemy的组合.
我的问题:
当我向数据库中已存在的对象发送请求到api时,SQLAlchemy显示异常:
IntegrityError: (IntegrityError) column <column_name> is not unique u'INSERT INTO ...
Run Code Online (Sandbox Code Playgroud)
所以我尝试添加属性validation_exceptions到create_api方法:
manager.create_api( ... , validation_exceptions=[IntegrityError])
Run Code Online (Sandbox Code Playgroud)
但响应json包含:
{
"validation_errors": "Could not determine specific validation errors"
}
Run Code Online (Sandbox Code Playgroud)
和服务器api显示异常:
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
Run Code Online (Sandbox Code Playgroud)
Flask-restless中的异常验证不适用于此类异常(IntegrityError)
我该怎么办?是否有可能为异常创建一些处理程序并在json中返回我自己的错误消息?
您可以使用预处理器来捕获验证错误。
def validation_preprocessor(data, *args, **kwargs):
# validate data by any of your cool-validation-frameworks
if errors:
raise ProcessingException(description='Something went wrong', code=400)
manager.create_api(
Model,
methods=['POST'],
preprocessors=dict(
POST=[validation_preprocessor]
)
)
Run Code Online (Sandbox Code Playgroud)
但我不确定这是一个好方法。
| 归档时间: |
|
| 查看次数: |
1260 次 |
| 最近记录: |