3
我使用的是從mimerender異常映射(讓我們以JSON作爲例子),但是輸出不同於當一個請求工作:瓶和mimerender異常處理
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'}
這怎麼能實現?
確實是這樣,我忘了這仍然是開放的,我現在已經想通了,但我想知道我是否可以操縱'例外'c姑娘?無論如何感謝您的迴應:-) – user1839924