gpt4 book ai didi

python - Flask 和 mimerender 异常处理

转载 作者:行者123 更新时间:2023-11-28 17:49:09 25 4
gpt4 key购买 nike

我正在使用 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'}

如何实现?

最佳答案

显然 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)})

关于python - Flask 和 mimerender 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13480675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com