文章目录
前言
本文内容为参考网络资源,学习整理得出,仅供学习使用,参考资料在文末,若有侵权,立即删除。
简介
Flask是轻量级的Pyhton的Web框架
安装
pip install flask
基础编程
requirements文件的使用
Python
项目中必须要有一个requirements.txt
文件来记录依赖包及具体版本号,以便在新环境中部署
- 将当前虚拟环境中的所有依赖包及其版本号生成到
requirement.txt
文件中:pip freeze > requirements.txt
- 在新环境中安装项目所需的所有特定版本的依赖包:
pip install -r requirements.txt
路由
- URL与视图
python
@app.route('/hello', methods = ['GET', 'POST'])
def hello_world():
return 'Hello World'
- 默认为
GET
方法 - 路由参数处理
python
@app.route('/hello/<id>')
def hello_world(id):
if id == str(1):
return 'flask'
else:
return 'Hello World'
<>
为正则匹配(注:默认传递的id
为string
类型如果要在代码中匹配<>
中内容,需要以字符串形式进行判断或匹配);也可在<>
中指定类型,如@app.route('/hello/<string:id>')
或@app.route('/hello/<int:id>')
等- 根据路由显示相应内容
python
@app.route('/hello/<id>')
def hello_world(id):
return 'Hello World %s' % id
request
包含前端发送的所有请求数据。(request.method
获取请求方式)- 重定向302:
redirect(...)
- 返回
json
数据给前端:
python
app.config['JSON_AS_ASCII'] = False
return jsonify(...)
abort
函数(在页面中抛出异常):abort(404)
- 自定义异常
python
@app.errorhandler(404)
def handle_404_error(err):
...
- 消息闪现:
flash(u'测试')
Jinja2
Jinja2
是由Python
实现的模板语言
- 模板渲染
- 展示
index.html
网页
- 展示
python
@app.route('/')
def hello_world():
return render_template("index.html")
- HTML中的参数使用
- 注释:
{#注释#}
- 变量代码块:
{``{url}}
- 通常,模板中使用的变量名和要传递的变量名保持一致。
- 控制代码块:
{% if a == 1 %}
- 注释:
python
@app.route('/<my_id>')
def hello_world(my_id):
return render_template("index.html", my_id = my_id)
- 过滤器
- 自定义过滤器
- 注册过滤器:
app.add_template_filter(自定义函数名字,'用时的名字')
- 注册过滤器:
- 自定义过滤器
- WTF表单
- 定义表单模型类
python
class Test(FlaskForm):
uname = StringField(label = '用户名', validators = [DataRequired('用户名不能为空')])
...
submit = SubmitField('label = '提交')
- 使用表单
python
@app.route('/test')
def test():
form = Test()
return render_template('test.html', form = form)
- 验证器
validate_on_submit
:form.validate_on_submit()
Restful
REST(Representational State Transfer)表现层状态转换
- 详见Flask Restful官方文档
- 前后端分离,前后端都遵循Restful编程规范,开发效率高,便于管理。
- 协议使用
http
或https
协议;数据传输应采用json
格式;url中不能有动词,只能有名词,且名词要注意单复数;状态码。 - 安装:
pip install flask-restful
- Restful API的要素
- 端点-URL
- HTTP请求方式
GET
:获取数据POST
:新增数据PUT
:修改数据DELETE
:删除数据
- 头部信息(Request,Response)
- 请求数据(要发送给服务的具体数据)
- 基本使用
- 引入
flask-restful
python
from flask_restful import Api
api = Api(app)
- 定义资源类:写一个类视图(继承子
Resource
类),在其中定义响应的请求方法(如get
、post
等);最后使用api.add_resource
来添加类视图与url
。
python
from flask_restful import Resource
class ManResource(Resource):
def get(self, id):
return {'id': id, 'name': 'Tom'}
def put(self, id):
return {'id': id, 'name': 'Mike'}
...
api.add_resource(ManResource, '/man/<id>')
- 可以指定多个
url
,也可传递参数。
- 参数验证(参数解析)
- 通过
flask_restful.reqparse
中RequestParser
建立解析器 - 通过
RequestParser
中的add_argument
方法定义字段与解析规则 - 通过
RequestParser
中的parse_args
来解析参数- 解析正确:返回正确的参数
- 解析错误:返回错误信息给前端
python
from flask import Flask
from flask_restful import Api, Resource
from flask_restful.reqparse import RequestParser
app = Flask(__name__)
api = Api(app)
class RegisterView(Resource):
def post(self):
# 建立解析器
parser = RequestParser()
# 定义数据的解析规则
parser.add_argument('username',type=str,required=True, trim = True, help = '用户名不符合规范')
parser.add_argument('age', type=int, help='年龄验证错误')
parser.add_argument('gender', type=str, choices = ['男', '女', '保密'], help = '性别验证错误')
# 解析数据:正确,直接获取参数;错误,反馈到前端
args = parser.parse_args()
print(args)
# 响应数据
return {'msg': '注册成功'}
api.add_resource(RegisterView, '/register/')
if __name__ == '__main__':
app.run()
add_argument
方法参数
default
:默认值required
:是否必须,默认为False
,若为True
则这个参数必须提交。type
:这个参数的数据类型,可以为int
、str
等,也可以为:url
、regex
、date
(若文件类型:FileStorage
)choices
:固定选项help
:错误信息trim
:是否去掉前后空格
- 规范返回值
- 导入
flask_restful.marshal_with
装饰器 - 定义一个字典变量来指定需要返回的标准化字段以及该字段的数据类型。
python
from flask import Flask
from flask_restful import Api, Resource, fields, marshal_with
app = Flask(__name__)
api = Api(app)
class Test_0():
def __init__(self, code, msg):
self.code = code
self.msg = msg
class Test(Resource):
resource_fields = {
'code':fields.Integer,
'msg':fields.String
}
@marshal_with(resource_fields)
def get(self):
return {'code':200, 'msg': '访问成功'}
@marshal_with(resource_fields)
def post(self):
return {'msg': '注册成功'}
@marshal_with(resource_fields)
def put(self):
# 在返回对象时会自动获取约定好的字段,并封装成json返回
test = Test_0(404, 'OK')
return test
api.add_resource(Test,'/test/')
if __name__ == '__main__':
app.run()
-
自定义
fields
- 写一个类继承
Raw
- 重写
format
方法
pythonclass My_fields(Raw): def format(self): return 结果
- 写一个类继承
-
实现"点击跳转
url
":定义两个fields
... -
参数设置
- 设置重命名属性:使用
attribute
,重命名后属性名称与后端数据库等操作字段匹配(实现前端显示与后端命名不一致) - 设置默认值:使用
default
(约束字段中的默认值的优先级低于真实数据默认值的优先级)
- 设置重命名属性:使用
python
from flask import Flask
from flask_restful import Api, Resource, fields, marshal_with
app = Flask(__name__)
api = Api(app)
class Test_0():
def __init__(self, code, message):
self.code = code
self.message = message
class Test(Resource):
resource_fields = {
# 通过default设置默认值
'code':fields.Integer(default=666),
# 通过attribute设置返回值
'msg':fields.String(attribute = 'message')
}
@marshal_with(resource_fields)
def get(self):
test = Test_0(404, 'OK')
return test
@marshal_with(resource_fields)
def post(self):
return {'message': '测试'}
api.add_resource(Test,'/test/')
if __name__ == '__main__':
app.run()
- 类型设置
fields.List()
存放一个列表fields.Nested()
存放一个字典- 若要返回自定义类的对象
marshal(对象, 对象的fields格式)
、marshal([对象, 对象], 对象的fields格式)
@marshal_with(my_fields)
函数需要参数,参数就是最终的数据输出格式。
- 结合蓝图使用
- 渲染模版
- 使用
api.representation
装饰器定义函数,在函数中对html
代码进行封装,再返回。(api.representation
装饰器修饰的函数必须返回一个Response
对象)
- 生成swagger文档
使用pip install
安装apispec
、flask apispec
和PyYAML
或在requirements.txt
中添加这几个包及具体版本号。
- CBV(Class Based View)类视图
- FBV(Function Based View)函数视图