flask模板应用-消息闪现(flash()) --

消息闪现

flask提供了一个非常有用的flash()函数,它可以用来“闪现”需要提示给用户的消息,比如当用户登录成功后显示“欢迎回来!”。在视图函数调用flash()函数,传入消息内容,flash()函数把消息存储在session中,我们需要在模板中使用全局函数get_flashed_messages()获取消息并将它显示出来。

通过flash()函数发送的消息会存储在session对象中,所以我们需要为程序设置秘钥。可以通过app.secret_key属性或配置变量SECRET_KEY设置。

你可以在任意视图函数中调用flash()函数发送消息。例如:

just_flash视图中,通过flash()函数发送一条消息,然后重定向到index视图。

 
@app.route('/flash')
def just_flash():
    flash('I am flash, who is looking for me?')
    return redirect(url_for('watchlist'))
 
flask提供了get_flashed_message()函数用来在模板里获取消息,因为程序的每一个页面都有可能需要显示消息,我们把获取并显示消息的代码放到基模板中content块的上面,这样就可以在页面主体内容上面显示消息
 

在base.html模板中加入处理闪现消息的函数:

因为同一个页面可能包含多条要显示的消息,所以这里使用for循环遍历get_flashed_message()返回的消息列表。

1 <main>
2     {% for message in get_flashed_messages() %}
3         <div class="alert">{{ message }}</div>
4     {% endfor %}
5     {% block content %}{% endblock %}
6 </main>

也可以的定义一些CSS规则,放在static/syles.CSS文件中

访问127.0.0.1:5000/打开程序的主页,单击页面上的Flash something链接(指向/flash),页面重载后就会显示一条消息,如图:

当get_flashed_message()函数被调用时,session中存储的所有消息都会被移除。如果这时刷新页面,会发现重载后的页面不再出现这条消息。

jinja2内部使用unicode编码类型,所以需要向模板传递unicode对象或只包含ASCII字符的字符串。在python2中,如果字符串包含中文,需要在字符串前加u前缀,告诉python把该字符串编码成unicode格式,另外还需要在python文件的首行添加编码声明,这会让python使用utf-8来解码字符串。

在html文件中的head标签中添加编码声明:<meta charset=”utf-8”>

例子用到的主体代码和文件:

在网页上先访问路径127.0.0.1:5000,触发index视图,index视图对应的模板index.html,继承自基模板base.html,两个html文件构成网页主体内容,在index.html中有两个链接分别链接到watchlist视图和just_flash视图,触发的just_flash视图时会触发闪现消息。

代码:
from flask import flash

app.secret_key = 'secret string'

@app.route('/flash')
def just_flash():
    flash('I am flash, who is looking for me?')
    return redirect(url_for('index'))

@app.route('/watchlist')
def watchlist():
    return render_template('watchlist.html',user=user,movies = movies)

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

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

base.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    {% block head %}
        <title>{% block title %}Template - HelloFlask{% endblock %}</title>
        <link rel="icon" type="image/x-icon" href="{{ url_for('static', filename='favicon.ico') }}">
        {% block styles %}
            <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='style.css' ) }}">
        {% endblock %}
    {% endblock %}
</head>
<body>
<nav>
    <ul><li><a href="{{ url_for('index') }}">Home</a></li></ul>
</nav>

<main>
    {% for message in get_flashed_messages() %}
        <div class="alert">{{ message }}</div>
    {% endfor %}
    {% block content %}{% endblock %}
</main>
<footer>
    {% block footer %}
        <small> &copy; 2019 <a href="https://www.cnblogs.com/xiaxiaoxu/" title="xiaxiaoxu's blog">夏晓旭的博客</a> /
            <a href="https://github.com/xiaxiaoxu/hybridDrivenTestFramework" title="Contact me on GitHub">GitHub</a> /
            <a href="http://helloflask.com" title="A HelloFlask project">Learning from GreyLi's HelloFlask</a>
        </small>
    {% endblock %}
</footer>
{% block scripts %}{% endblock %}
</body>
</html>
index视图对应的模板index.html
 1 {% extends 'base.html' %}
 2 {% from 'macro.html' import qux %}
 3 
 4 {% block content %}
 5 {% set name='baz' %}
 6 <h1>Template</h1>
 7 <ul>
 8     <li><a href="{{ url_for('watchlist') }}">Watchlist</a></li>
 9     <li><a href="{{ url_for('hello') }}">xiaxiaoxu</a></li>
10     <li>Filter: {{ foo|musical }}</li>
11     <li>Global: {{ bar() }}</li>
12     <li>Test: {% if name is baz %}I am baz.{% endif %}</li>
13     <li>Macro: {{ qux(amount=1) }}</li>
14     <li><a href="{{ url_for('just_flash') }}">Flash something</a></li>
15 </ul>
16 {% endblock %}

watchlist链接对应的模板watchlist.html
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>{{ user.username }}'s Watchlist</title>
 6     <styles>
 7         <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename= 'style.css' ) }}">
 8     </styles>
 9 </head>
10 <body>
11 <a href = "{{ url_for('index') }}">&larr; Return</a>
12 <h2><img src="{{ url_for('static', filename='qq.jpg') }}" width="50">{{ user.username }}</h2>
13 {% if user.bio %}
14     <i>{{ user.bio }}</i>
15 {% else %}
16     <i>This user has not provided a bio.</i>
17 {% endif %}
18 {# 下面是电影清单(这是注释) #}
19 <h5>{{ user.username }}'s Watchlist ({{ movies|length }}):</h5>
20 <ul>
21     {% for movie in movies %}
22         <li>{{ movie.name }} - {{ movie.year }}</li>
23     {% endfor %}
24 </ul>
25 </body>
26 </html>
宏文件,macro.html

宏qux在index.html中用到

 1 % macro qux(amount=1) %}
 2     {% if amount == 1 %}
 3         I am qux.
 4     {% elif amount > 1 %}
 5         We are quxs.
 6     {% endif %}
 7 {% endmacro %}
 8 
 9 {% macro static_file(type, filename_or_url, local=True) %}
10     {% if local %}
11         {% set filename_or_url = url_for('static', filename=filename_or_url) %}
12     {% endif %}
13 {% if type == 'CSS' %}
14     <link rel="stylesheet" href="{{ filename_or_url }}" type="text/css">
15 {% elif type == 'js' %}
16     <scirpt type ="text/javascript" src="{{ filename_or_url }}"></scirpt>
17 {% elif type == 'icon' %}
18     <link rel="icon" href="{{ filename_or_url }}">
19 {% endif %}
20 {% endmacro %}
样式CSS文件
 1 body {
 2     margin: auto;
 3     width: 750px;
 4 }
 5 
 6 nav ul {
 7     list-style-type: none;
 8     margin: 0;
 9     padding: 0;
10     overflow: hidden;
11     background-color: #333;
12 }
13 
14 nav li {
15     float: left;
16 }
17 
18 nav li a {
19     display: block;
20     color: white;
21     text-align: center;
22     padding: 14px 16px;
23     text-decoration: none;
24 }
25 
26 nav li a:hover {
27     background-color: #111;
28 }
29 
30 main {
31     padding: 10px 20px;
32 }
33 
34 footer {
35     font-size: 13px;
36     color: #888;
37     border-top: 1px solid #eee;
38     margin-top: 25px;
39     text-align: center;
40     padding: 10px;
41 
42 }
43 
44 .alert {
45   position: relative;
46   padding: 0.75rem 1.25rem;
47   margin-bottom: 1rem;
48   border: 1px solid transparent;
49   border-radius: 0.25rem;
50   color: #004085;
51   background-color: #cce5ff;
52   border-color: #b8daff;
53 }

网页整体链接情况

flash消息

watchlist:return链接是返回到主页

xiaxiaoxu链接:

 

原文地址:https://www.cnblogs.com/xiaxiaoxu/p/10468103.html