【问题标题】:How to JSON format an HTTP error response in webapp2如何在 webapp2 中对 HTTP 错误响应进行 JSON 格式设置
【发布时间】:2013-03-16 22:16:52
【问题描述】:

我正在使用 webapp2 在 App Engine 中进行开发。我想做的是在发生错误时发送自定义 JSON 格式的响应。例如当请求长度大于阈值时,使用 HTTP 400 和响应正文进行响应

{'error':'InvalidMessageLength'}

在 webapp2 中,可以选择为某些异常分配错误处理程序。例如:

app.error_handlers[400] = handle_error_400

其中 handle_error_400 如下:

def handle_error_400(request, response, exception):
    response.write(exception)
    response.set_status(400)

webapp2.RequestHandler.abort(400)被执行时,上面的代码就被执行了。

如何根据上述设置动态地获得不同的响应格式(HTML 和 JSON)?也就是怎么可能调用不同版本的handle_error_400函数呢?

【问题讨论】:

    标签: json google-app-engine error-handling webapp2


    【解决方案1】:

    这是一个完整的示例,它演示了如何为所有类型的错误使用相同的错误处理程序,如果您的 URL 以 /json 开头,那么响应将是 application/json(请发挥您的想象力)充分利用request 对象来决定您应该提供什么样的响应):

    import webapp2
    import json
    
    def handle_error(request, response, exception):
      if request.path.startswith('/json'):
        response.headers.add_header('Content-Type', 'application/json')
        result = {
            'status': 'error',
            'status_code': exception.code,
            'error_message': exception.explanation,
          }
        response.write(json.dumps(result))
      else:
        response.write(exception)
      response.set_status(exception.code)
    
    app = webapp2.WSGIApplication()
    app.error_handlers[404] = handle_error
    app.error_handlers[400] = handle_error
    

    在上面的示例中,您可以通过访问以下 URL 轻松测试不同的行为,这些 URL 将返回 404,这是最容易测试的错误:

    http://localhost:8080/404
    http://localhost:8080/json/404
    

    【讨论】:

      猜你喜欢
      • 2017-09-11
      • 1970-01-01
      • 2012-06-19
      • 1970-01-01
      • 2016-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      相关资源
      最近更新 更多