在金字塔中如何用json数据返回400响应?

发布于 2024-11-24 21:10:32 字数 754 浏览 0 评论 0原文

我有以下 jquery 代码:

$.ajax({
    type: 'POST',
    url: url,
    data: data,
    dataType: 'json',
    statusCode: {
        200: function (data, textStatus, jqXHR) {
                console.log(data);
            },
        201: function (data, textStatus, jqXHR) {
                 log(data);
            },
        400: function(data, textStatus, jqXHR) {
                log(data);
            },
    },
});

当后端(金字塔)验证失败时使用 400。现在,如何从 Pyramid 返回 HTTPBadRequest() 响应以及包含验证错误的 json 数据?我尝试了类似的方法:

response = HTTPBadRequest(body=str(error_dict)))
response.content_type = 'application/json'
return response

但是当我在 firebug 中检查时,它返回 400 (错误请求),这很好,但它永远不会解析上面 data.responseText 的 json 响应。

I have the following jquery code:

$.ajax({
    type: 'POST',
    url: url,
    data: data,
    dataType: 'json',
    statusCode: {
        200: function (data, textStatus, jqXHR) {
                console.log(data);
            },
        201: function (data, textStatus, jqXHR) {
                 log(data);
            },
        400: function(data, textStatus, jqXHR) {
                log(data);
            },
    },
});

the 400 is used when the validation in backend (Pyramid) fails. Now from Pyramid how do I return HTTPBadRequest() response together with a json data that contains the errors of validation? I tried something like:

response = HTTPBadRequest(body=str(error_dict)))
response.content_type = 'application/json'
return response

But when I inspect in firebug it returns 400 (Bad Request) which is good but it never parses the json response from data.responseText above.

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

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

发布评论

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

评论(3

灯角 2024-12-01 21:10:32

好吧,您可能应该首先使用 json 库序列化 error_dict

import json
out = json.dumps(error_dict)

鉴于您没有提供有关如何设置视图的任何上下文,我只能向您展示我将如何做到这一点:

@view_config(route_name='some_route', renderer='json')
def myview(request):
    if #stuff fails to validate:
        error_dict = # the dict
        request.response.status = 400
        return {'errors': error_dict}

    return {
        # valid data
    }

如果您想自己创建响应,那么:

response = HTTPBadRequest()
response.body = json.dumps(error_dict)
response.content_type = 'application/json'
return response

要调试问题,请停止基于 jQuery 是否工作并亲自查看请求以确定 Pyramid 是否正常运行,或者是否存在其他问题。

curl -i <url>

或者甚至只是在浏览器中打开调试器来查看响应中返回的内容。

Well you should probably start off by serializing the error_dict using a json library.

import json
out = json.dumps(error_dict)

Given that you don't give any context on how your view is setup, I can only show you how I would do it:

@view_config(route_name='some_route', renderer='json')
def myview(request):
    if #stuff fails to validate:
        error_dict = # the dict
        request.response.status = 400
        return {'errors': error_dict}

    return {
        # valid data
    }

If you want to create the response yourself, then:

response = HTTPBadRequest()
response.body = json.dumps(error_dict)
response.content_type = 'application/json'
return response

To debug the issue, stop going based off of whether jQuery works and look at the requests yourself to determine if Pyramid is operating correctly, or if it is something else that's going on.

curl -i <url>

Or even just open up the debugger in the browser to look at what is being returned in the response.

做个少女永远怀春 2024-12-01 21:10:32

我找到了一种简单的方法,比接受的答案更通用,我用这段代码得到了它,我

在我的视图中包含了 exception_response

from pyramid.httpexceptions import exception_response

我在需要的地方引发了 400 异常

 raise exception_response(400)

在我的异常脚本中,我捕获所有异常以返回通用 json 和我捕获 400 返回特定的 json

from pyramid.view import exception_view_config

from pyramid.httpexceptions import (
    HTTPException,
    HTTPBadRequest
)


@exception_view_config(HTTPException, renderer='json')
def exc_view_exception(message, request):
    return {'error': str(message)}


@exception_view_config(HTTPBadRequest, renderer='json')
# Exception 400 bad request
def exc_view_bad_request(message, request):
    body = {
        "message": str(message),
        "status": 400
    }
    request.response.status = 400
    return body

I found a simple way to do it more generic then the accepted answer, I got it with this code

I include exception_response in my view

from pyramid.httpexceptions import exception_response

I raise the 400 exception where I need to

 raise exception_response(400)

In my exceptions script, I trap all exceptions to return generic json and I trap 400 to return a specific json

from pyramid.view import exception_view_config

from pyramid.httpexceptions import (
    HTTPException,
    HTTPBadRequest
)


@exception_view_config(HTTPException, renderer='json')
def exc_view_exception(message, request):
    return {'error': str(message)}


@exception_view_config(HTTPBadRequest, renderer='json')
# Exception 400 bad request
def exc_view_bad_request(message, request):
    body = {
        "message": str(message),
        "status": 400
    }
    request.response.status = 400
    return body
简单爱 2024-12-01 21:10:32

您可以更改响应状态代码,如下所示:request.response.status_code = 400。以下示例对我有用

@view_config(route_name='qiwiSearch', request_method='GET', renderer='json')
def qiwiSearchGet(request):
    schema = SchemaQiwiSearchParams()
    try:
        params = schema.deserialize(request.GET)
    except colander.Invalid, e:
        errors = e.asdict()
        request.response.status_code = 400
        return dict(code=400, status='error', message=unicode(errors))

    log.debug(u'qiwiSearchGet: %s' % params)
    return dict(code=200, status='success', message='', data=[1,2,3])

You can change response status code like this: request.response.status_code = 400. Following examle is working for me

@view_config(route_name='qiwiSearch', request_method='GET', renderer='json')
def qiwiSearchGet(request):
    schema = SchemaQiwiSearchParams()
    try:
        params = schema.deserialize(request.GET)
    except colander.Invalid, e:
        errors = e.asdict()
        request.response.status_code = 400
        return dict(code=400, status='error', message=unicode(errors))

    log.debug(u'qiwiSearchGet: %s' % params)
    return dict(code=200, status='success', message='', data=[1,2,3])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文