代码之家  ›  专栏  ›  技术社区  ›  Natim

如何使用django活塞返回格式化的错误消息和正确的HTTP代码?

  •  1
  • Natim  · 技术社区  · 14 年前

    我想能够返回一个HTTP响应与django活塞格式化的内容。

    rc_factory

    我想做的是:

    return rc.404({'status': 0,'message': 'This restaurant does not exists.'})
    

    我该怎么做?

    干杯

    1 回复  |  直到 14 年前
        1
  •  1
  •   Natim    14 年前

    你怎么看这样的事情:

    # -*- coding: utf-8 -*-
    from piston.handler import typemapper
    from piston.emitters import Emitter
    
    def getErrorResponse(http_code, payload, em_format='json'):
            emitter, ct = Emitter.get(em_format)
            srl = emitter(payload, typemapper, handler=None, anonymous=False)
            r = srl.render({})
            return HttpResponse(r, content_type=ct, status=http_code)
    

    像这样使用:

    return getErrorResponse(404, {'status': 0,'message': 'This restaurant does not exists.'})
    

    实际上,hander方法可以通过在handler函数中添加带有emitter\u format属性的来获取此信息。

    ...
        def read(self, request, emitter_format=None):
            if emitter_format is None:
                emitter_format = request.GET.get('format', 'json')
    
            ...
            return getErrorResponse(404, {'status': 0,'message': 'This restaurant does not exists.'}, emitter_format)