Flask框架重定向,错误显示,Responses响应及Sessions会话操作示例

yipeiwu_com5年前Python基础

本文实例讲述了Flask框架重定向,错误显示,Responses响应及Sessions会话操作。分享给大家供大家参考,具体如下:

重定向和错误显示

将用户重定向到另一个端点,使用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()

默认情况下,会为每个错误代码显示黑白错误页面,如果要自定义错误页面,请使用errorhandler() 装饰器.

Responses

  1. 如果返回了正确类型的响应对象,则直接从视图返回。
  2. 如果是字符串,则使用该数据和默认参数创建响应对象。
  3. 如果返回元组,则元组中的项可以提供额外信息。这样的元组必须是这样的形式,或者至少有一个项必须在元组中。该值将覆盖状态代码,可以是其他标头值的列表或字典。(response, status, headers)或者是(response, 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

Sessions会话追踪

session在cookie的基础上实现的,并以加密方式对cookie进行签名

要使用sessions,必须要设置私钥,以下是简单示例:

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实现通过微信搜索功能查看谁把你删除了

基于Python实现通过微信搜索功能查看谁把你删除了

场景:查找who删了我,直接copy代码保存到一个python文件who.py,在python环境下运行此文件 代码如下,copy保存到who.py文件在python环境直接运行:...

python高级特性和高阶函数及使用详解

python高级特性和高阶函数及使用详解

python高级特性 1、集合的推导式 •列表推导式,使用一句表达式构造一个新列表,可包含过滤、转换等操作。 语法:[exp for item in collection i...

Python 获取主机ip与hostname的方法

->基础环境 Linux:ubuntu 16.04 Python ; 2.7 ->修改hostname 1:$sudo hostname 2tong-slavetwo 2:$...

python和flask中返回JSON数据的方法

python和flask中返回JSON数据的方法

在python中可以使用json将数据格式化为JSON格式: 1.将字典转换成JSON数据格式: s=['张三','年龄','姓名'] t={} t['data']=s ret...

Python字符串格式化%s%d%f详解

关于讨论输出格式化的问题,小编不是一时兴起,之前学习python的时候就经常遇到输出时“%d”,一直没有仔细学习,今天又看到了,下面分享一个简单实例,python输出99乘法表: #...