1、模板的简单使用
使用jinja2模板
- 在templates文件夹下创建.html模板文件
- 导入render_template方法
- 在相应视图函数中返回渲染的模板
@app.route('/')
def hello_world():
return render_template('index.html')
使用参数导入
@app.route('/')
def hello_world():
cotent='Hello World'
return render_template('index.html',content=cotent)
渲染模板html文件:注意双花括号传入参数
<body>
<h1>{{ content }}</h1>
</body>
2、条件语句
模板代码
<body>
{% if user %}
hello {{ user.user_name }}
{% else %}
Hello Strange!
{% endif %}
</body>
视图代码模板
@app.route('/query_user/<user_id>')
def query_user(user_id):
user=None
if int(user_id)==1:
user=User(1,'helloworld')
return render_template('user_id.html',user=user)
3、循环语句
html代码模板
<body>
{% for user in users %}
<li>hello{{ user.user_id }}--{{ user.user_name }}</li>
{% endfor %}
</body>
视图函数代码模板
@app.route('/users')
def user_list():
users=[]
for i in range(11):
user=User(i,'helloworld'+str(i))
users.append(user)
return render_template('user_list.html',users=users)
4、模板的继承
模板的主题内容不变,不变的部分为基类,变化的部分为子类 基类代码示例——使用{%block}
<div>
<h1>Header Hello World</h1>
</div>
{% block content%}
{% endblock %}
<div>
<h1>Footer Hello</h1>
</div>
子类代码——使用{%extends 'base.html'}继承基类
{% extends 'base.html' %}
{% block content %}
这是第1页
{% endblock %}
4
、消息提示
使用flash作为消息提示
- 导入flash
- 需要配置app.secret_key=' ',flask使用其进行加密
- 在视图函数中flash('消息提示')
- 在模板中{{get_flashed_messages()}}获取消息
用户登录作为例子:
@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=='zhouzhou' and password=='123456':
flash('login success')
return render_template('index.html')
else:
flash('username or password is wrong')
return render_template('index.html')
模板
<body>
<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>
5、抛出异常
使用errorhandler()来解决异常,使用abort来抛出异常
@app.errorhandler(404)
def page_notfound(e):
return render_template('404.html')
模板
<body>
<h1>抱歉页面不存在</h1>
</body>
6、异常处理捕获异常
@app.route('/users/<userid>')
def user(userid):
if int(userid)==1:
return render_template('user.html')
else:
abort(404)