Abort () function abort custom status code

A profile,

When we write the view function, we check the parameters passed by the front end, and if the check fails, we return some specific exception information to the front end. In Flask, the abort() function immediately terminates the view function and returns the corresponding error message to the front end.

Second, the use of

from flask import Flask, abort

app = Flask(__name__)


@app.route('/login/<phone>')
def index(phone):
    ifphone ! ='123456':
        abort(502)  Stop executing the view function immediately and return the exception
    return phone


if __name__ == '__main__':
    # 0.0.0.0 means that any address that represents the machine is accessible
    app.run(host='0.0.0.0', port=5000, debug=True)  # run the program

Copy the code

Let’s debug the browser:

The status code consists of three digits. The first number defines the categories of the response. There are five categories:

  • 1XX: Indicating message – indicating that the request has been received and processing continues
  • 2xx: Success: The request is successfully received, understood, or accepted
  • 3xx: Redirect – Further action must be taken to complete the request
  • 4XX: Client error – The request has a syntax error or the request cannot be implemented
  • 5xx: server side error — the server failed to implement a valid request common status code:
401 Unauthorized // The Request is Unauthorized. This status code must be used with the www-Authenticate header field using 403 Forbidden // The server received the request but refused to provide the service 404 Not Found // The requested resource did Not exist, eg: An incorrect URL is entered. 500 Internal Server Error // An unexpected Error occurs on the Server. 503 Server Unavailable // The Server cannot process requests from the clientCopy the code

3. Customize status code information

Sometimes we feel that the default status code message is unfriendly to the user. We can change the default status code message to what we want. We add the following function to the project:

# Customize 502 status code information
@app.errorhandler(502)
def handle_502_error(error):  # error: Indicates an error message
    return "The server went to pick up some girls."
Copy the code

Let’s debug the browser: