模板
在templates
文件夹下面
语法是{{ }}
获取参数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
{{ context }}
welcome {{ user.getName() }}
</body>
</html>
__author__ = 'Nicholas'
class User():
def __init__(self,name,password):
self.name = name
self.password = password
def getName(self):
return self.name
def setName(self,name):
self.name = name
def setPassword(self,password):
self.password = password
__author__ = 'Nicholas'
from flask import Flask,render_template
from model import User
app = Flask(__name__)
@app.route('/')
def hello():
context = 'hello template'
return render_template('index.html',context = context)
@app.route('/user')
def user():
user = User('zhangsan','zhangsan')
return render_template('index.html',user = user)
if __name__=='__main__':
app.run()
条件语句
语法格式
{% if condition %}
{% else %}
{% endif %}
{% if user %}
hello ,{{ user.getName() }}
{% else %}
sorry,no such user !
{% endif %}
循环语句
语法格式
{% for user in users %}
{% endfor %}
{% for user in users %}
{{ user.getName() }} -- {{ user.password }}
{% endfor %}
模板继承
把一个页面中,不变的部分抽象成一个基类,变化的部分在子类中实现
基类 base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div>
<h1>头部信息栏,每个页面都是一样的部分</h1>
</div>
<!--中间变化的部分,做成一个block-->
{% block context %}
{% endblock %}
<div>
<h1>底部信息栏,每个页面都是一样的部分</h1>
</div>
</body>
</html>
子类
one.html
<!--继承父类-->
{% extends "base.html" %}
<!--实现父类的部分-->
{% block context%}
<h2> 这是子类</h2>
{% endblock %}
消息提示与异常处理
消息闪现机制
- 声明
app.secret_key
= ‘123’ - 调用flush
from flask import Flask, flash, render_template, request,abort
app = Flask(__name__)
app.secret_key = '123'
@app.route('/')
def hello_world():
flash("hello")
return render_template("index.html")
@app.route('/login', methods=['POST'])
def login():
form = request.form
username = form.get('username')
password = form.get('password')
if not username:
flash("please input username")
return render_template("index.html")
if not password:
flash("please input password")
return render_template("index.html")
if username == 'weixuan' and password == '123456':
flash("login success")
return render_template("index.html")
else:
flash("username or password is wrong")
return render_template("index.html")
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>Hello Login</h1>
<form action="/login" method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="submit" value="Submit">
</form>
<h2>{{ get_flashed_messages()[0] }}</h2>
</body>
</html>
异常处理
@app.errorhandler(404)
处理异常
@app.errorhandler(404)
def not_found(e):
return render_template("404.html")
@app.route('/users/<user_id>')
def users(user_id):
if int(user_id) == 1:
return render_template("user.html")
else:
abort(404)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>该页面不存在</h1>
</body>
</html>