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

发布于 2024-09-25 23:55:53 字数 303 浏览 2 评论 0原文

我希望能够使用 django-piston 返回带有格式化内容的 HTTP 响应。

我想我必须创建自己的rc_factory

我想做的是:

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

使用 XMLEmiter、JSONEmiter 或 YAMLEmiter 提供的关于客户端正在寻找的格式的结果。

我怎样才能做到这一点?

干杯

I would like to be able to return a HTTP Reponse with a formated content with django-piston.

I guess I have to create my own rc_factory.

What I would like to do is :

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

With a result provide by XMLEmiter, JSONEmiter or YAMLEmiter regarding to the format the client is looking for.

How can I do that ?

Cheers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦魇绽荼蘼 2024-10-02 23:55:53

您如何看待这样的事情:

# -*- 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.'})

但问题来自于 em_format 属性。

实际上hander方法可以通过在处理函数中添加emitter_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)

What do you think of somthing like this :

# -*- 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)

To use like this :

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

But the problem comes from the em_format attribute.

Actually the hander method is able to get this information by adding the with the emitter_format attribute in the handler function.

...
    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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文