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')

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>

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)

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)

序列化和返序列化

序列化:可以理解为把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>
@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'))

Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐