Python Flask,如何返回 ajax 调用的成功状态码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26079754/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask, how to return a success status code for ajax call
提问by yayu
On the server-side, I am just printing out the json-as-dictionary to the console
在服务器端,我只是将 json-as-dictionary 打印到控制台
@app.route('/',methods=['GET','POST'])
@login_required
def index():
if request.method == "POST":
print request.json.keys()
return "hello world"
Now, whenever I make a post request via ajax, the console prints out the dictionary with the contents I need.
现在,每当我通过 ajax 发出 post 请求时,控制台都会打印出包含我需要的内容的字典。
On the client-side, I have been trying to use various methods to execute some jquery based on a successfull ajax call. I just realized that this might be an error on my server-side, i.e I am not sending any request header to tell jquery that its ajax call was a success.
在客户端,我一直在尝试使用各种方法基于成功的 ajax 调用来执行一些 jquery。我刚刚意识到这可能是我的服务器端的错误,即我没有发送任何请求头来告诉 jquery 它的 ajax 调用是成功的。
So how do I send an OK status back to my client to tell it everything is all right?
那么我如何向我的客户发送 OK 状态以告诉它一切正常?
For the sake of completeness, here is my clientside code
为了完整起见,这是我的客户端代码
$.ajax({
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(myData),
dataType: 'json',
url: '/',
success: function () {
console.log("This is never getting printed!!")
}});
采纳答案by aabilio
About Responsesin Flask:
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 OKstatus code and atext/htmlmimetype. The logic that Flask applies to converting return values into response objects is as follows:
- If a response object of the correct type is returned it's directly returned from the view.
- If it's a string, a response object is created with that data and the default parameters.
- 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. Thestatusvalue will override the status code andheaderscan be a list or dictionary of additional header values.- If none of that works, Flask will assume the return value is a valid WSGI application and convert that into a response object.
关于回复
视图函数的返回值会自动转换为您的响应对象。如果返回值是一个字符串,它会被转换为一个响应对象,该字符串作为响应主体、一个
200 OK状态代码和一个text/htmlmimetype。Flask 将返回值转化为响应对象的逻辑如下:
- 如果返回正确类型的响应对象,它将直接从视图返回。
- 如果它是一个字符串,则使用该数据和默认参数创建一个响应对象。
- 如果返回元组,元组中的项目可以提供额外信息。此类元组必须采用以下形式,
(response, status, headers)或者元组中必须(response, headers)至少包含一项。该status值将覆盖状态代码,并且headers可以是附加标头值的列表或字典。- 如果这些都不起作用,Flask 将假定返回值是一个有效的 WSGI 应用程序并将其转换为响应对象。
So, if you return text string (as you are doing), the status code that your AJAX call has to receive is 200 OK, and your success callback must be executing. However, I recommend you to return a JSON formatted response like:
因此,如果您返回文本字符串(正如您所做的那样),您的 AJAX 调用必须接收的状态代码是200 OK,并且您的成功回调必须正在执行。但是,我建议您返回 JSON 格式的响应,例如:
return json.dumps({'success':True}), 200, {'ContentType':'application/json'}
回答by Philip Bergstr?m
As an option to aabilio's answer, you can use the jsonify method in Flask which automatically sets the Content-Type:
作为aabilio 答案的一个选项,您可以使用 Flask 中的 jsonify 方法,它会自动设置 Content-Type:
from flask import jsonify
resp = jsonify(success=True)
return resp
You can (optionally) set the response code explicitly:
您可以(可选)显式设置响应代码:
resp.status_code = 200
回答by seyisulu
In addition to the answers already posted, I find using the make_responsemethod in Flask (from version 0.6) to be a clearer alternative especially when you need to return status codes with the response JSON for APIs from Flask:
除了已经发布的答案之外,我发现使用make_responseFlask 中的方法(从 0.6 版开始)是一个更清晰的选择,尤其是当您需要使用 Flask 的 API 响应 JSON 返回状态代码时:
from flask import jsonify, make_response
# ... other code ...
data = {'message': 'Created', 'code': 'SUCCESS'}
return make_response(jsonify(data), 201)
Also, this approach will automatically set the Content-Typeheader to application/json.
此外,这种方法会自动将Content-Type标题设置为application/json.
回答by Martlark
When returning a response using jsonifyjust add the status_codeas the second parameter of the return. I've used jsonifyin this admin_required decorator with the 401 unauthorized HTTP code. Example:
当使用jsonify仅添加status_code作为return. 我jsonify在这个 admin_required 装饰器中使用了 401 未经授权的 HTTP 代码。例子:
return jsonify({'error': 'Admin access is required'}), 401
Full example:
完整示例:
def admin_required(f):
@wraps(f)
def decorated(*args, **kwargs):
if current_user and hasattr(current_user, 'user_type') and current_user.user_type == 'admin':
return f(*args, **kwargs)
else:
if '/api/' in request.url_rule.rule:
return jsonify({'error': 'Admin access is required'}), 401
flash(_('Admin access required'))
return redirect(url_for('main.public_index'))
return decorated

