【问题标题】:How to override notfound() in web.py for a REST API?如何为 REST API 覆盖 web.py 中的 notfound()?
【发布时间】:2013-09-10 00:15:05
【问题描述】:

我试图了解如何使用 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?

【问题讨论】:

    标签: json rest python-2.7 web.py


    【解决方案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,你可能想检查一下,相信我它有一些有趣的想法。

    【讨论】:

      猜你喜欢
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 2022-10-18
      • 1970-01-01
      • 2019-01-31
      相关资源
      最近更新 更多