【Flask】基础入门

文章目录

前言

本文内容为参考网络资源,学习整理得出,仅供学习使用,参考资料在文末,若有侵权,立即删除。

简介

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'
  • <>为正则匹配(注:默认传递的idstring类型如果要在代码中匹配<>中内容,需要以字符串形式进行判断或匹配);也可在<>中指定类型,如@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_submitform.validate_on_submit()

Restful

REST(Representational State Transfer)表现层状态转换

  • 详见Flask Restful官方文档
  • 前后端分离,前后端都遵循Restful编程规范,开发效率高,便于管理。
  • 协议使用httphttps协议;数据传输应采用json格式;url中不能有动词,只能有名词,且名词要注意单复数;状态码。
  • 安装:pip install flask-restful
  1. Restful API的要素
    1. 端点-URL
    2. HTTP请求方式
      • GET:获取数据
      • POST:新增数据
      • PUT:修改数据
      • DELETE:删除数据
    3. 头部信息(Request,Response)
    4. 请求数据(要发送给服务的具体数据)
  2. 基本使用
  • 引入flask-restful
python 复制代码
from flask_restful import Api
api = Api(app)
  • 定义资源类:写一个类视图(继承子Resource类),在其中定义响应的请求方法(如getpost等);最后使用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,也可传递参数。
  1. 参数验证(参数解析)
  • 通过flask_restful.reqparseRequestParser建立解析器
  • 通过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()
  1. add_argument方法参数
  • default:默认值
  • required:是否必须,默认为False,若为True则这个参数必须提交。
  • type:这个参数的数据类型,可以为intstr等,也可以为:urlregexdate(若文件类型:FileStorage
  • choices:固定选项
  • help:错误信息
  • trim:是否去掉前后空格
  1. 规范返回值
  • 导入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方法
    python 复制代码
    class 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)函数需要参数,参数就是最终的数据输出格式。
  1. 结合蓝图使用
  2. 渲染模版
  • 使用api.representation装饰器定义函数,在函数中对html代码进行封装,再返回。(api.representation装饰器修饰的函数必须返回一个Response对象)
  1. 生成swagger文档
    使用pip install安装apispecflask apispecPyYAML或在requirements.txt中添加这几个包及具体版本号。
  • CBV(Class Based View)类视图
  • FBV(Function Based View)函数视图

参考资料

相关推荐
hqxstudying11 分钟前
SpringBoot相关注解
java·spring boot·后端
啊哈哈哈哈哈啊哈哈1 小时前
G9打卡——ACGAN
python·生成对抗网络·gan
ALLSectorSorft1 小时前
相亲小程序用户注册与登录系统模块搭建
java·大数据·服务器·数据库·python
Livingbody2 小时前
ubuntu25.04完美安装typora免费版教程
后端
阿华的代码王国2 小时前
【Android】RecyclerView实现新闻列表布局(1)适配器使用相关问题
android·xml·java·前端·后端
码农BookSea2 小时前
自研 DSL 神器:万字拆解 ANTLR 4 核心原理与高级应用
java·后端
lovebugs2 小时前
Java并发编程:深入理解volatile与指令重排
java·后端·面试
caisexi2 小时前
Windows批量启动java服务bat脚本
java·windows·python
海奥华22 小时前
操作系统到 Go 运行时的内存管理演进与实现
开发语言·后端·golang
codervibe2 小时前
Spring Boot 服务层泛型抽象与代码复用实战
后端