zoukankan      html  css  js  c++  java
  • flask中flash(闪现)的使用

    我们有时候在一个页面存储了一些信息,然后需要在另一个页面使用,这个时候就需要使用flash,其实从应用需求角度来看session也能完成上面的需求,其实flash就是对session的封装,它的底层实现其实也是session。

    首先我们看下flash 和 get_flashed_message这两个函数的源码

    def flash(message, category="message"):
        """Flashes a message to the next request.  In order to remove the
        flashed message from the session and to display it to the user,
        the template has to call :func:`get_flashed_messages`.
    
        .. versionchanged:: 0.3
           `category` parameter added.
    
        :param message: the message to be flashed.
        :param category: the category for the message.  The following values
                         are recommended: ``'message'`` for any kind of message,
                         ``'error'`` for errors, ``'info'`` for information
                         messages and ``'warning'`` for warnings.  However any
                         kind of string can be used as category.
        """
        # Original implementation:
        #
        #     session.setdefault('_flashes', []).append((category, message))
        #
        # This assumed that changes made to mutable structures in the session are
        # always in sync with the session object, which is not true for session
        # implementations that use external storage for keeping their keys/values.
        flashes = session.get("_flashes", [])
        flashes.append((category, message))
        session["_flashes"] = flashes
        message_flashed.send(
            current_app._get_current_object(), message=message, category=category
        )
    
    
    def get_flashed_messages(with_categories=False, category_filter=()):
        """Pulls all flashed messages from the session and returns them.
        Further calls in the same request to the function will return
        the same messages.  By default just the messages are returned,
        but when `with_categories` is set to ``True``, the return value will
        be a list of tuples in the form ``(category, message)`` instead.
    
        Filter the flashed messages to one or more categories by providing those
        categories in `category_filter`.  This allows rendering categories in
        separate html blocks.  The `with_categories` and `category_filter`
        arguments are distinct:
    
        * `with_categories` controls whether categories are returned with message
          text (``True`` gives a tuple, where ``False`` gives just the message text).
        * `category_filter` filters the messages down to only those matching the
          provided categories.
    
        See :ref:`message-flashing-pattern` for examples.
    
        .. versionchanged:: 0.3
           `with_categories` parameter added.
    
        .. versionchanged:: 0.9
            `category_filter` parameter added.
    
        :param with_categories: set to ``True`` to also receive categories.
        :param category_filter: whitelist of categories to limit return values
        """
        flashes = _request_ctx_stack.top.flashes
        if flashes is None:
            _request_ctx_stack.top.flashes = flashes = (
                session.pop("_flashes") if "_flashes" in session else []
            )
        if category_filter:
            flashes = list(filter(lambda f: f[0] in category_filter, flashes))
        if not with_categories:
            return [x[1] for x in flashes]
        return flashes
    
    

    从上面我可以再次认证flash就是利用session实现的。

    下面讲解下如何使用它。

    1、首先也是先引入它

    from flask imoport Flask,flash
    

    2、在需要的地方写入flash

    @app.route('/login', methods=['GET', 'POST'])
    def login():
        error = None
        if request.method == 'POST':
            if request.form['username'] != app.config['USERNAME']:
                error = 'Invalid username'
            elif request.form['password'] != app.config['PASSWORD']:
                error = 'Invalid password'
            else:
                session['logged_in'] = True
                flash('You were logged in')
                return redirect(url_for('index'))
        return render_template('login.html', error=error)
      
    

    3、在需要读取的地方进行读取

    {% for message in get_flashed_messages() %}
        <div class=flash>{{ message }}</div>
     {% endfor %}
    

    说明点:flash和它的名字一样,是闪现,意思就是我们的消息只会显示一次,当我们再次刷新也面的时候,它就不存在了,而正是这点,它经常被用来显示一些提示消息,比如登陆之后,显示欢迎信息等

  • 相关阅读:
    10gen发布MongoDB增量备份服务
    JSON.NET 5中的架构变更
    Snowbox 2.0 发布,POP3 邮件服务器
    资源监控工具 glances
    Druid 0.2.18 发布,阿里巴巴数据库连接池
    Groovy 更新到 2.0.8 and 2.1.3
    Apache Libcloud 0.12.4 发布,统一云计算接口
    Go1.1性能测试报告(和C差距在10%以内)
    Apache Camel 2.11.0 发布,规则引擎
    2010年01月01日0时0分 总结我的2009
  • 原文地址:https://www.cnblogs.com/itdreamfly/p/12871602.html
Copyright © 2011-2022 走看看