当前位置:   article > 正文

flask+layUI+mysql 列表和表单数据_flask layui

flask layui

flask+layUI+mysql
1、列表展示数据库中的数据:
首先通过’/student/跳转到列表界面

@user_blueprint.route('/student/', methods=['GET', 'POST'])
@is_login
def student():
    """学生信息列表"""
    if request.method == 'GET':
        return render_template('student_list.html')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

Js中调用url: ‘/user/get_student_list’ //数据接口获取json数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/layui/css/layui.css" media="all">
    <script src="/static/layui/layui.js" type="text/javascript" charset="UTF-8"></script>
    <script src="/static/js/jquery-3.2.1.min.js"></script>
</head>
<body>
hello
<table id="demo" lay-filter="test"></table>
<script>
layui.use('table', function(){
  var table = layui.table;

  //第一个实例
  table.render({
    elem: '#demo'
    ,height: 312
    ,url: '/user/get_student_list' //数据接口
    ,page: true //开启分页
    ,cols: [[ //表头
      {field: 's_id', title: 'ID', width:80, sort: true, fixed: 'left'}
      ,{field: 's_name', title: '用户名', width:80}
      ,{field: 's_sex', title: '性别', width:80, sort: true}
    ]]
  });

});
</script>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

route(‘/get_student_list/’, methods=[‘GET’, ‘POST’])提供Json数据
在数据库中查找信息,但获得信息是对象类,将每个对象转化为字典形式,再将字典转化为json

@user_blueprint.route('/get_student_list/', methods=['GET', 'POST'])
@is_login
def student_list():
    """学生信息列表"""
    if request.method == 'GET':
        page = int(request.args.get('page',1))
        page_num = int(request.args.get('page_num',5))
        paginate = Student.query.order_by('s_id').paginate(page,page_num)
        stus = paginate.items

        list=[]
        for item in stus:
            list.append(dict(item))
        print("list",list)
        #return render_template('student_list.html', stus=stus,paginate=paginate)
        data = {"code": 0, "msg": "", "count": 1000, "data":list}
        print("data",data)
        return jsonify(data)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

class里添加keys, __ getitem__(定义keys和__getitem__方法)使可以转化为字典形式

class Student(db.Model):
    s_id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    s_name = db.Column(db.String(16), unique=True)
    s_sex = db.Column(db.String(16))
    #grade_id = db.Column(db.Integer, db.ForeignKey('grade.g_id'), nullable=True)

    __tablename__ = 'student'

    def __init__(self, s_name, s_sex):
        self.s_name = s_name
        self.s_sex = s_sex
        #self.grade_id =grade_id

    def save(self):
        db.session.add(self)
        db.session.commit()
    def keys(self):
        return ('s_id','s_name','s_sex')
    def __getitem__(self, item):
        return getattr(self,item)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

序列化和返序列化

序列化:可以理解为把python的对象编码转行成json格式的字符串

------序列化就是把python内置数据类型(列表list,元组tuple,字典dict)转化成str

返序列化:可以理解为把json格式字符串解码为python数据对象

-----返序列化就是把str转化为python内置数据类型(列表list,字典dict)
2、表单数据返回存入数据库
表单中包括图片上传具体见flask +layUI+ ajax 上传图片

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/layui/css/layui.css" media="all">
    <script src="/static/layui/layui.js" type="text/javascript" charset="UTF-8"></script>
    <script src="/static/js/jquery-3.2.1.min.js"></script>
</head>
<body>
<form class="layui-form" id="form_show_json" action="">
  <div class="layui-form-item">
    <label class="layui-form-label">姓名</label>
    <div class="layui-input-block">
      <input type="text" name="s_name" required  lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input">
    </div>
  </div>


  <div class="layui-form-item">
    <label class="layui-form-label">性别</label>
    <div class="layui-input-block">
      <input type="radio" name="s_sex" value="" title="">
      <input type="radio" name="s_sex" value="" title="" checked>
    </div>
  </div>
  <div class="layui-form-item layui-form-text">
    <label class="layui-form-label">其他</label>
    <div class="layui-input-block">
      <textarea name="desc" placeholder="请输入内容" class="layui-textarea"></textarea>
    </div>
  </div>
  <div class="layui-form-item ">
    <div class="layui-input-block">
	  <input type="file" name="FileUpload" id="FileUpload" class=".layui-form-label ">
	  <a class="layui-btn layui-btn-mini" id="btn_uploadimg"><i class="layui-icon">&#xe67c;</i>上传图片</a>
    </div>
  </div>
  <div class="layui-form-item">
    <div class="layui-input-block">
      <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
    </div>
  </div>
</form>
<script>
//Demo
$(function () {
        $("#btn_uploadimg").click(function () {
            var fileObj = document.getElementById("FileUpload").files[0]; // js 获取文件对象
            if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
                alert("请选择图片");
                return;
            }
            var formFile = new FormData();
            formFile.append("action", "UploadVMKImagePath");
            formFile.append("file", fileObj); //加入文件对象

            //ajax 提交

            var form_data = formFile;
            console.log(form_data);
            console.log(form_data.append.name);
            $.ajax({
                url: "/user/upload",
                data: form_data,
                type: "post",
                dataType: "json",
                cache: false,//上传文件无需缓存
                processData: false,//用于对data参数进行序列化处理 这里必须false
                contentType: false, //必须
                success: function (result) {
                    alert("上传完成!");
                },
            })
        })
    })

layui.use('form', function(){
  var form = layui.form;

  //监听提交
  form.on('submit(formDemo)', function(data){
  console.log("form")
  console.log($('#form_show_json').serialize(),)
  $.ajax({
        type: 'POST',
        url: "/user/addstu/",
        dataType: "json",
        data: $('#form_show_json').serialize(),// 获取表单提交的数据
        success: function (data) {
          console.log(data)
          console.log("hello")
          alert("添加完成!");

        }
    });

<!--    layer.msg(JSON.stringify(data.field));-->
    return false;
  });
});
</script>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
@user_blueprint.route('/addstu/', methods=['GET', 'POST'])
@is_login
def add_stu():
    """添加学生"""
    if request.method == 'GET':
        #grades = Grade.query.all()
        return render_template('add_student.html')

    if request.method == 'POST':
        s_name = request.form.get('s_name')
        s_sex = request.form.get('s_sex')

        print("form_name",s_name)
        stu = Student.query.filter(Student.s_name == s_name).first()
        if stu:
            msg = '* 学生姓名不能重复'
            #grades = Grade.query.all()
            return render_template('add_student.html', msg=msg)
        stu = Student(s_name=s_name, s_sex=s_sex)
        stu.save()

        return redirect(url_for('user.student'))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/158039
推荐阅读
相关标签
  

闽ICP备14008679号