我试图了解如何使用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内容类型?
答案 0 :(得分:1)
web.py中的HTTP错误应该作为例外引发。
我用这个类来装饰json错误(它在我的应用程序中有特定的输出格式,所以你可以根据自己的需要采用它):
class NotFoundError(web.HTTPError):
'''`404 Not Found` error.'''
headers = {'Content-Type': 'application/json'}
def __init__(self, note='Not Found', headers=None):
status = '404 Not Found'
message = json.dumps([{'note': note}])
web.HTTPError.__init__(self, status, headers or self.headers,
unicode(message))
我创建了一个简单的json api with web.py,您可能需要查看,相信我有一些有趣的想法。