我的Javascript中有一个(jQuery)AJAX调用调用Python方法服务器端验证一个人是否有凭据,然后Python发回所需的信息。
如果此人未登录或没有凭据,则会抛出错误并在我的jQuery AJAX函数中捕获错误块中的错误,告诉用户发生了错误。
我的问题是我无法显示哪种错误,只是发生了错误并且服务器返回了500代码。即使用户没有凭据,我是否应该成功完成该方法,而是返回“禁止”或“未登录”而不是所需数据的消息?
基本上我的问题是,当用户无权访问某些信息时,我是否应强制该方法抛出异常?
答案 0 :(得分:1)
是的,你应该抛出异常。您应该不返回服务器错误的成功响应,因为服务的使用者可能不知道您实际存储的是否是特定信息,如果是错误,如果是,则是什么类型。< / p>
此外,您可以修改回发HTTP 403的响应消息,这实际上会传达授权失败。
答案 1 :(得分:1)
401
错误用于身份验证,403
用于授权。这样做的方法是使用自定义错误处理程序:
from flask import Flask, abort, Response, jsonify
app = Flask(__name__)
@app.errorhandler(403)
def not_authorized(e):
response = jsonify({'code': 403,'message': 'Not damn authorized'})
response.status_code = 403
return response
@app.errorhandler(401)
def not_authenticated(e):
response = jsonify({'code': 401,'message': 'Not damn authenticated'})
response.status_code = 401
return response
@app.route("/unauthorized")
def unauthorized():
abort(403)
@app.route("/unauthenticated")
def unauthenticated():
abort(401)
@app.route("/")
def index():
return jsonify({"message":"hello world!"})
#Another way to do it perhaps, without using global error handler functions.
@app.route("/test/<var>")
def test(var):
if var == 1:
response = jsonify({'code': 403,'message': 'Not damn authorized'})
response.status_code = 403
return response
else:
response = jsonify({'code': 403,'message': 'Some other message'})
response.status_code = 403
return response
if __name__ == "__main__":
app.run(port=8080, debug=True)