【问题标题】:Is there a a way to change the default content-type to all Bottle's error responses at once?有没有办法一次将默认内容类型更改为所有 Bottle 的错误响应?
【发布时间】:2015-03-17 05:30:03
【问题描述】:

我正在 Bottle 中创建一个小型 REST API。

我只想通过响应返回 JSON,虽然我可以为每个 HTTP 状态代码使用错误装饰器 @error(status_code),所以它输出 JSON,但我觉得这很长而且不太实用。

有人知道更好的方法吗?

【问题讨论】:

    标签: json python-2.7 bottle


    【解决方案1】:

    好的,所以我想我已经设法做到这一点,虽然我不知道它的内存/编程效率如何:

    import bottle
    import json
    app = bottle.default_app()  # or bottle.app()
    
    for http_code in bottle.HTTP_CODES:
        @app.error(http_code)
        def json_error(error):
            bottle.response.default_content_type = "application/json"
            return json.dumps(dict(error=error.status_code, message=error.status_line))
    

    【讨论】:

      猜你喜欢
      • 2011-10-29
      • 2019-08-23
      • 2018-09-25
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-14
      相关资源
      最近更新 更多