flask 基础
flask 路由
from app import app
@app.route('/')
@app.route('/index')
def index():
return "Hello, World index!"
@app.route('/susz')
def susz():
return "Hello, susz World view"
@app.route('/lff')
def lff():
return "Hello, lff World view"
可通过以下三个地址访问
http://192.168.2.105:5000
http://192.168.2.105:5000/lff
http://192.168.2.105:5000/susz
flask 模板
@app.route('/')
@app.route('/index')
def index():
# return "Hello, index"
user = { 'nickname': 'Miguel' } # fake user
return render_template("index.html",
title = 'Home',
user = user,
susz = 'susz'
)
index.html
<html>
<head>
<title>{{susz}}-{{title}} - microblog</title>
</head>
<body>
<h1>Hello, {{susz}},{{user.nickname}}!</h1>
</body>
</html>
模板中控制语句和循环语句
def index():
user = { 'nickname': 'Miguel' } # fake user
posts = [ # fake array of posts
{
'author': { 'nickname': 'John' },
'body': 'Beautiful day in Portland!'
},
{
'author': { 'nickname': 'Susan' },
'body': 'The Avengers movie was so cool!'
}
]
return render_template("index.html",
title = 'Home',
user = user,
posts = posts)
<html>
<head>
{% if title %}
<title>{{title}} - microblog</title>
{% else %}
<title>microblog</title>
{% endif %}
</head>
<body>
<h1>Hi, {{user.nickname}}!</h1>
{% for post in posts %}
<p>{{post.author.nickname}} says: <b>{{post.body}}</b></p>
{% endfor %}
</body>
</html>
网页结果如下
Hi, Miguel!
John says: Beautiful day in Portland!
Susan says: The Avengers movie was so cool!
模板继承
index.py 不改变,新增加文件app/templates/base.html
<html>
<head>
{% if title %}
<title>{{title}} - microblog</title>
{% else %}
<title>microblog</title>
{% endif %}
</head>
<body>
<div>Microblog: <a href="/index">Home</a></div>
<hr>
{% block content %}{% endblock %}
</body>
</html>
修改html.index如下
{% extends "base.html" %}
{% block content %}
<h1>Hi, {{user.nickname}}!</h1>
{% for post in posts %}
<div><p>{{post.author.nickname}} says: <b>{{post.body}}</b></p></div>
{% endfor %}
{% endblock %}
在这个模板中,我们使用 block 控制语句来定义派生模板可以插入的地方。块被赋予唯一的名字。现在剩下的就是修改我们的 index.html 模板继承自 base.html
运行结果如下:
Microblog: Home
Hi, Miguel!
John says: Beautiful day in Portland!
Susan says: The Avengers movie was so cool!