Flask 简明教程

Flask – Redirect & Errors

Flask 类有一个 redirect() 函数。当被调用时,它返回一个响应对象,并且使用指定的HTTP状态码将用户重定向到另一个目标位置。

Flask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code.

redirect() 函数的原型如下 −

Prototype of redirect() function is as below −

Flask.redirect(location, statuscode, response)

在上面的函数中 −

In the above function −

  1. location parameter is the URL where response should be redirected.

  2. statuscode sent to browser’s header, defaults to 302.

  3. response parameter is used to instantiate response.

以下状态代码是标准化的 −

The following status codes are standardized −

  1. HTTP_300_MULTIPLE_CHOICES

  2. HTTP_301_MOVED_PERMANENTLY

  3. HTTP_302_FOUND

  4. HTTP_303_SEE_OTHER

  5. HTTP_304_NOT_MODIFIED

  6. HTTP_305_USE_PROXY

  7. HTTP_306_RESERVED

  8. HTTP_307_TEMPORARY_REDIRECT

default status 代码是 302 ,用于 ‘found’

The default status code is 302, which is for ‘found’.

在以下示例中, redirect() 函数用于在登录尝试失败时再次显示登录页面。

In the following example, the redirect() function is used to display the login page again when a login attempt fails.

from flask import Flask, redirect, url_for, render_template, request
# Initialize the Flask application
app = Flask(__name__)

@app.route('/')
def index():
   return render_template('log_in.html')

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST' and request.form['username'] == 'admin' :
      return redirect(url_for('success'))
   else:
      return redirect(url_for('index'))

@app.route('/success')
def success():
   return 'logged in successfully'

if __name__ == '__main__':
   app.run(debug = True)

Flask 类具有带错误代码的 abort() 函数。

Flask class has abort() function with an error code.

Flask.abort(code)

Code 参数采用以下值之一 −

The Code parameter takes one of following values −

  1. 400 − for Bad Request

  2. 401 − for Unauthenticated

  3. 403 − for Forbidden

  4. 404 − for Not Found

  5. 406 − for Not Acceptable

  6. 415 − for Unsupported Media Type

  7. 429 − Too Many Requests

让我们在上述代码中的 login() 函数中做一些小的更改。如果要显示 ‘Unauthourized’ 页面,请用调用 abort(401) 替换重新显示登录页面。

Let us make a slight change in the login() function in the above code. Instead of re-displaying the login page, if ‘Unauthourized’ page is to be displayed, replace it with call to abort(401).

from flask import Flask, redirect, url_for, render_template, request, abort
app = Flask(__name__)

@app.route('/')
def index():
   return render_template('log_in.html')

@app.route('/login',methods = ['POST', 'GET'])
def login():
   if request.method == 'POST':
      if request.form['username'] == 'admin' :
         return redirect(url_for('success'))
      else:
         abort(401)
   else:
      return redirect(url_for('index'))

@app.route('/success')
def success():
   return 'logged in successfully'

if __name__ == '__main__':
   app.run(debug = True)