Flask框架重定向、错误处理、响应对象及会话管理详解

巷口听风
巷口听风
发布时间:2026-10-14| 5人浏览过
原创

本文详细介绍Flask框架中的核心功能,包括使用redirect和abort实现重定向与错误中止,通过errorhandler自定义错误页面,解析Response对象的创建与修改机制,以及利用secret_key配置基于Cookie加密的Session会话追踪。

本文详细介绍Flask框架中关于重定向、错误显示、响应对象(Responses)以及会话(Sessions)的操作示例,供Python开发者参考。

重定向与错误处理

重定向与错误处理

在Flask中,可使用redirect()函数将用户重定向至其他端点;若需提前终止错误请求,则应使用abort()函数。


from flask import abort, redirect, url_for
@app.route('/')
def index():
  return redirect(url_for('login'))
@app.route('/login')
def login():
  abort(401)
  this_is_never_executed()

默认情况下,Flask会为每个错误代码显示黑白的默认错误页面。若需自定义错误页面,请使用errorhandler()装饰器进行配置。

响应对象处理

响应对象处理

  1. 若视图返回的是正确类型的响应对象,则可直接从视图返回该对象。
  2. 若返回的是字符串,Flask会使用该数据及默认参数自动创建响应对象。
  3. 若返回元组,元组中的项可提供额外信息。元组形式应为(response, status, headers)或至少包含一个项,其中status用于覆盖状态代码,headers可为列表或字典形式的其他标头值。

若需在视图中获取生成的响应对象,可使用make_response()函数。

假设存在如下视图代码:


@app.errorhandler(404)
def not_found(error):
  return render_template('error.html'), 404

通过调用make_response()函数包含返回表达式,获取响应对象并进行修改后返回。


@app.errorhandler(404)
def not_found(error):
  resp = make_response(render_template('error.html'), 404)
  resp.headers['X-Something'] = 'A value'
  return resp

会话追踪机制

会话追踪机制

Session功能基于Cookie实现,并对Cookie内容进行加密签名以确保安全。

使用Session前必须设置私钥,以下是一个简单示例:


from flask import Flask, session, redirect, url_for, escape, request
app = Flask(__name__)
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
@app.route('/')
def index():
  if 'username' in session:
    return 'Logged in as %s' % escape(session['username'])
  return 'You are not logged in'
@app.route('/login', methods=['GET', 'POST'])
def login():
  if request.method == 'POST':
    session['username'] = request.form['username']
    return redirect(url_for('index'))
  return '''
    <form method="post">
      <p><input type=text name=username>
      <p><input type=submit value=Login>
    </form>
  '''
@app.route('/logout')
def logout():
  # remove the username from the session if it's there
  session.pop('username', None)
  return redirect(url_for('index'))

希望上述内容能帮助读者更好地掌握基于Flask框架的Python程序设计技巧。

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。