Flask框架(下)
一、Flask-Script扩展命令使用
安装
pip install Flask-Script
导入Manager
from flask_script import Manager
创建Manager对象
manager = Manger(app)
使用manager对象的run()方法(而不使用app.run())
manager.run()
接下来就可以像django的manage.py一样,使用命令来操作
1、查看有哪些命令
python xxx.py --help
2、常用命令
启动服务器
python xx.py runserver
进入该环境(模块)下命令模式
python xx.py shell
注:flask2.0版本会报错
处理方法:在flask_script/__init__.py文件里面把from ._compat import text_type 改成 from flask_script._compat import text_type
二、模板(Jinja2模板)
1、Flask模板渲染函数
from flask import render_template
- render_template("模板文件",参数1= 值1, 参数2 = 值2, ...)方法
- return render_template("index.html", name = "fy", age = 18)
data = {参数1:值1, 参数2:值2, ...}
#通过拆包的方式也能使用字典
render_template("模板文件",**data)方法
2、模板变量的基本使用(与django模板变量使用类似)
3、过滤器
一、使用语法
{ {模板变量或字符串 | 过滤器}}
{ {模板变量或字符串 | 过滤器1 | 过滤器2 |...}}
从左到右执行过滤器二、字符串过滤器
safe:禁用转义
{ {"<em>hello</em>" | safe}}
capitalize:把变量值的首字母转换成大写,其余字母转小写
lower:把值转换成小写
upper:把值转换成大写
title:把值中的每个单词的首字母都转成大写
trim:把值的首尾空格去掉
reverse:字符串反转
format:格式化输出
<p>{ {"<%s is %d> | format("name", 17)"}}
striptags:渲染之前把值中所有的HTML标签都删掉
三、列表过滤器
first:取第一个元素
last:取最后一个元素
length:获取列表长度
sum:列表求和
sort:列表排序
四、自定义过滤器
方式一:
通过app.add_template_filter(过滤器函数, 模板中使用的过滤器名字)方法
例:
def filter_double_sort(ls):
return ls[::2]
app.add_template_filter(filter_double_sort, "double_2")
方式二:
通过装饰器app.template_filter(模板中使用的装饰器名字)
例:
@app.template_filter("double_3")
def filter_double_sort(ls):
return ls[::-3]
过滤器原理:模板中把参数值传递给过滤器函数,函数的返回值就是过滤后该参数的值
4、Flask-WTF表单扩展
帮助进行csrf验证,帮助我们快速定义表单模板,而且帮助我们在视图中验证表单数据
安装:pip install Flask-WTF
使用步骤:
1、通过类抽象出表单
from flask_wtf import FlaskForm #定义表单模型类 class RegisterForm(FlaskForm): """自定义注册表单模型类""" pass
2、类属性定义表单的字段
from flask_wtf import FlaskForm from wtfroms import StringField, PasswordField, SubmitField #导入表单字段-flask_wtf依赖包 from wtforms.validators import DataRequird, EqualTo #导入验证器-flask_wtf依赖包 #定义表单模型类 class RegisterForm(FlaskForm): """自定义注册表单模型类""" # label说明标签 validators验证器,可以有多个。 user_name = StringField(label="用户名", validators=[DataRequired("用户名不能为空")]) password = PasswordField(label="用户名", validators=[DataRequired("密码不能为空")]) rpassword = PasswordField(label="用户名", validators=[DataRequired("确认密码不能为空")],EqualTo("password", "两次密码不一致")) submit = SubmitField(label = "提交")
wtf支持的表单字段
wtf常用验证函数