Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 在金字塔中,如何使用json数据返回400响应?_Jquery_Python_Pyramid - Fatal编程技术网

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

Jquery 在金字塔中,如何使用json数据返回400响应?,jquery,python,pyramid,Jquery,Python,Pyramid,我有以下jquery代码: $.ajax({ type: 'POST', url: url, data: data, dataType: 'json', statusCode: { 200: function (data, textStatus, jqXHR) { console.log(data); }, 201: function (data, textStatus

我有以下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响应。

您可能应该首先使用json库序列化
错误

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>
curl-i

甚至只需在浏览器中打开调试器,查看响应中返回的内容。

您可以更改如下响应状态代码:request.response.status\u 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])

我找到了一个简单的方法,比公认的答案更通用,我用这段代码得到了它

我在我的观点中包含了异常响应

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

谢谢,我也用同样的方法计算出来了。:)如果您使用的是json呈现程序,并且仍然希望返回httpexception,那么您必须使用
raise response
而不是
return response
,而不是刚刚发现的--bump--我认为至少在当前版本中,它应该是
request.response.status=400
而不是
request.response.status\u int=400
yes?没关系,显然,当将
.status
设置为整数时,金字塔会自动为您填充文本。但愿我能在文件里找到