Flask,如何返回ajax的成功状态代码

2024-05-04 17:52:36 发布

您现在位置:Python中文网/ 问答频道 /正文

在服务器端,我只是将json作为字典输出到控制台

@app.route('/',methods=['GET','POST'])
@login_required
def index():
    if request.method == "POST":
        print request.json.keys()
    return "hello world"

现在,每当我通过ajax发出post请求时,控制台就会打印出包含所需内容的字典。

在客户端,我一直在尝试使用各种方法来执行基于成功ajax调用的jquery。我刚刚意识到这可能是服务器端的一个错误,即我没有发送任何请求头来告诉jquery它的ajax调用是成功的。

那么我该如何发送一个OK状态回我的客户告诉它一切都好?

为了完整起见,这是我的客户端代码

$.ajax({
    type: 'POST',
    contentType: 'application/json',
    data: JSON.stringify(myData),
    dataType: 'json',
    url: '/',
    success: function () {
        console.log("This is never getting printed!!")
    }});

Tags: jsonapp客户端get字典requestdef服务器端
3条回答

作为aabilio's answer的选项,可以在烧瓶中使用jsonify方法,该方法自动设置内容类型:

from flask import jsonify

resp = jsonify(success=True)
return resp

您可以(可选)显式设置响应代码:

resp.status_code = 200

烧瓶中的About Responses

About Responses

The return value from a view function is automatically converted into a response object for you. If the return value is a string it's converted into a response object with the string as response body, a 200 OK status code and a text/html mimetype. The logic that Flask applies to converting return values into response objects is as follows:

  1. If a response object of the correct type is returned it's directly returned from the view.
  2. If it's a string, a response object is created with that data and the default parameters.
  3. If a tuple is returned the items in the tuple can provide extra information. Such tuples have to be in the form (response, status, headers) or (response, headers) where at least one item has to be in the tuple. The status value will override the status code and headers can be a list or dictionary of additional header values.
  4. If none of that works, Flask will assume the return value is a valid WSGI application and convert that into a response object.

因此,如果返回文本字符串(正如您所做的那样),那么AJAX调用必须接收的状态代码是200 OK,并且成功回调必须正在执行。但是,我建议您返回一个JSON格式的响应,如:

return json.dumps({'success':True}), 200, {'ContentType':'application/json'} 

除了已经发布的答案之外,我发现在Flask中使用^{}方法(从0.6版开始)是一个更清晰的选择,特别是当您需要从Flask返回带有响应JSON的api状态代码时:

from flask import jsonify, make_response

# ... other code ...
data = {'message': 'Created', 'code': 'SUCCESS'}
return make_response(jsonify(data), 201)

此外,此方法将自动将Content-Type头设置为application/json

相关问题 更多 >