3

我正在使用来自 mimerender 的异常映射(我们以 json 为例),但是输出与请求工作时不同:

import json
import mimerender
...

mimerender = mimerender.FlaskMimeRender()

render_xml = lambda message: '<message>%s</message>'%message
render_json = lambda **args: json.dumps(args)
render_html = lambda message: '<html><body>%s</body></html>'%message
render_txt = lambda message: message

render_xml_exception = lambda exception: '<exception>%s</exception>'%exception
render_json_exception = lambda exception: json.dumps(exception.args)
render_html_exception = lambda exception: '<html><body>%s</body></html>'%exception
render_txt_exception = lambda exception: exception

@mimerender.map_exceptions(
    mapping=(
        (ValueError, '500 Internal Server Error'),
        (NotFound, '404 Not Found'),
    ),
    default = 'json',
    html = render_html_exception,
    xml  = render_xml_exception,
    json = render_json_exception,
    txt  = render_txt_exception
)
@mimerender(
    default = 'json',
    html = render_html,
    xml  = render_xml,
    json = render_json,
    txt  = render_txt
)
def test(...

当请求有效时,我得到以下响应:

* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: application/json
< Content-Length: 29
< Vary: Accept
< Server: Werkzeug/0.8.3 Python/2.7.3rc2
< Date: Tue, 20 Nov 2012 19:27:30 GMT
< 
* Closing connection #0
{"message": "Success"}

当请求失败并触发异常时:

* HTTP 1.0, assume close after body
< HTTP/1.0 401 Not Found
< Content-Type: application/json
< Content-Length: 25
< Vary: Accept 
< Server: Werkzeug/0.8.3 Python/2.7.3rc2
< Date: Tue, 20 Nov 2012 19:16:45 GMT
< 
* Closing connection #0
["Not found"]

我的问题:除了我想要相同类型的输出,如下所示:

{'message': 'Not found'}

如何做到这一点?

4

1 回答 1

2

显然exception.args是一个列表,并且它被这样返回:-) 要更改它,只需更改您返回的数据结构。

换句话说,改变:

render_json_exception = lambda exception: json.dumps(exception.args)

至:

render_json_exception = lambda exception: json.dumps({"message": exception.args})

或者,如果您必须在出错时只返回一条消息:

render_json_exception = lambda exception: json.dumps({"message": " - ".join(exception.args)})
于 2012-11-21T15:33:21.143 回答