Flask阅读笔记(二):基本用法

创建模板

假设我们需要编写一个用户的电影清单页面,类似于IMDb的watchlist页面的简易版,模板中要显示用户信息以及用于收藏的电影列表,包含电影的名字和年份,我们首先创建一份虚拟数据用于测试显示效果:

    user = {
                'username': 'Grey Li',
                'bio': 'A boy who loves movies and music.',
                }

    movies = [
                    {'name': 'My Neighbor Totoro', 'year': '1988',
                    {'name': 'Three Colours trilogy', 'year': '1993'},
                    {'name': 'Forrest Gump', 'year': '1994'},
                    {'name': 'Perfect Blue', 'year': '1997'},
                    {'name': 'The Matrix', 'year': '1999'},
                    {'name': 'Memento', 'year': '2000'},
                    {'name': 'The Bucket list', 'year': '2007'},
                    {'name': 'Black Swan', 'year': '2010'},
                    {'name': 'Gone Girl', 'year': '2014'},
                    {'name': 'CoCo', 'year': '2017'},
                    ]

我们的结构是:

其中视图函数放在app.py中,模板放在watchlist.html中,其实也有涉及到index视图函数和index.html,后面讲会讲到

app.py中的内容:

from flask import Flask, render_template

app = Flask(__name__)


user = {
    'username': 'Grey Li',
    'bio': 'A boy who loves movies and music.',
}

movies = [
    {'name': 'My Neighbor Totoro', 'year': '1988'},
    {'name': 'Three Colours trilogy', 'year': '1993'},
    {'name': 'Forrest Gump', 'year': '1994'},
    {'name': 'Perfect Blue', 'year': '1997'},
    {'name': 'The Matrix', 'year': '1999'},
    {'name': 'Memento', 'year': '2000'},
    {'name': 'The Bucket list', 'year': '2007'},
    {'name': 'Black Swan', 'year': '2010'},
    {'name': 'Gone Girl', 'year': '2014'},
    {'name': 'CoCo', 'year': '2017'},
]


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

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



watchlist中的内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>{{ user.username }}'s Watchlist</title>
</head>
<body>
<a href="{{ url_for('index') }}">&larr; Return</a>
<h2>{{ user.username }}</h2>
{% if user.bio %}
    <i>{{ user.bio }}</i>
{% else %}
    <i>This user has not provided a bio.</i>
{% endif %}
{# Below is the movie list (this is comment) #}
<h5>{{ user.username }}'s Watchlist ({{ movies|length }}):</h5>
<ul>
    {% for movie in movies %}
    <li>{{ movie.name }} - {{ movie.year }}</li>
    {% endfor %}
</ul>
</body>
</html>

注意:在模板中使用的← 是HTML实体。这里会显示为左箭头

实际显示效果

在控制台,通过以下语句启动flask服务

set FLASK_ENV=development
set FLASK_APP=app.py
flask run

访问http://127.0.0.1:5000/

猜你喜欢

转载自www.cnblogs.com/cnhkzyy/p/10430026.html