我试图了解如何使用 web.py 作为 REST 框架来处理 HTTP 错误代码。我可以轻松地使用 try/catch 块来返回 HTTP 404、400、500 等……但我很难用它发送自定义 JSON 消息。
import web
import json
urls = (
'/test/(.*)', 'Test'
)
app = web.application(urls, globals())
def notfound():
return web.notfound(json.dumps({'test': 'test'}))
class Test:
def GET(self, id):
web.header('Content-Type', 'application/json')
return self.get_resource(str(id))
def get_resource(self, id):
result = {}
if id == '1':
result = {'1': 'one'}
elif id == '3':
return web.notfound()
return json.dumps(result)
if __name__ == '__main__':
web.config.debug = False
app.notfound = notfound
app.run()
这很好用,但是当 时id == 3
,我无法覆盖该行为,并且Content-Type
标题被复制:
# curl -i -H "Accept: application/json" http://localhost:8080/test/3
HTTP/1.1 404 Not Found
Content-Type: application/json
Content-Type: text/html
Transfer-Encoding: chunked
Date: Mon, 09 Sep 2013 23:59:28 GMT
Server: localhost
404 Not Found
如何返回带有自定义消息的 JSON Content-Type?