HTTP status code setting guide
Introduction:
HTTP (Hypertext Transfer Protocol) is a protocol used to transmit hypertext. It passes between the client and the server. Communicate between requests and responses. During the HTTP communication process, the server will return a status code to indicate the processing result of the request. The correct setting of status codes is crucial to ensure normal network communication. This article will introduce the basic concepts of HTTP status codes and provide some status code setting examples in common scenarios.
1. Classification of HTTP status codes:
The first number of the HTTP status code indicates the five types of responses:
1xx: Informational status code (Informational)
2xx: Success Status code (Successful)
3xx: Redirection status code (Redirection)
4xx: Client error status code (Client Error)
5xx: Server error status code (Server Error)
2. Common HTTP status codes and their meanings:
3. HTTP status code setting example:
Return 200 OK:
@app.route('/') def index(): return 'Hello, World!', 200
Return 301 Moved Permanently:
@app.route('/old_url') def old_url(): return redirect(url_for('new_url'), code=301) @app.route('/new_url') def new_url(): return 'This is the new URL', 200
Returns 400 Bad Request:
@app.route('/login', methods=['POST']) def login(): if not request.json or 'username' not in request.json: abort(400) # 其他逻辑处理 return 'Login successful!', 200
Returns 403 Forbidden:
@app.route('/admin') def admin(): if not session.get('is_admin'): abort(403) # 管理员页面的逻辑处理 return 'Welcome, admin!', 200
Returns 404 Not Found:
@app.route('/user/<username>') def user_profile(username): # 根据username查询用户信息 if not user_exists(username): abort(404) # 用户信息展示页面的逻辑处理 return render_template('user_profile.html', username=username)
Returns 500 Internal Server Error:
@app.route('/validate') def validate(): # 一些验证逻辑 try: # 验证过程中可能引发的异常 if not validate_something(): raise Exception('Validation failed') except Exception as e: app.logger.error(str(e)) abort(500) # 其他逻辑处理 return 'Validation completed!', 200
Conclusion:
By correctly setting the HTTP status code, the server Ability to better communicate with clients and convey the results of request processing. In actual development, rational selection and setting of HTTP status codes based on business scenarios and needs will help improve user experience and system maintainability.
The above is the detailed content of Guide to Common HTTP Status Codes. For more information, please follow other related articles on the PHP Chinese website!