【发布时间】:2016-09-27 04:01:49
【问题描述】:
我有以下代码sn-p:
try:
DBSession.query(Task).filter_by(id=task_id).one()
except NoResultFound:
raise HTTPNotFound
我想将此作为application/json 响应返回。它适用于 try 子句,但是,如果引发异常 - 它会返回为 text/html。我知道我可以像这样手动构建响应:
response = HTTPNotFound()
response.content_type = 'application/json'
response.text = {'message': 'not found'}
return response
但是,每次都这样做很不方便。另一种可能的解决方案是使用@view_config装饰器:
@view_config(context=HTTPNotFound, renderer='json')
def not_found(request):
return {'message': 'not found'}
然后使用此视图引发该异常。但是,我不能使它应用广泛。如果我将此视图函数移动到__init__.py,它将停止被调用。所以我的问题是,如何从我在应用程序中提出的任何异常中返回json 响应而不是html?
【问题讨论】:
-
@view_config与config.scan()一起使用,你可以用config.add_view(...)替换它,它会做同样的事情。现在你可以把它放在你的__init__.py。