flask-vue_todolist-curd实例练习

一、前言
总览:
在这里插入图片描述
之前实现两个curd的demo,一个是只用vue在前端前端,一个是只用flask主要实现后端的接口,这次是将flask-vue结合起来实现将数据实际增删改到数据库的curd。但没有使用vue-cli,因为vue-cli和flask两个不是一个端口,也不是一个域,进行数据请求(axios)时会产生跨域问题,要想解决这个问题应该是要设置服务器,通过nginx的反向代理来解决,但最近主要是想实现对数据库的数据操作。所以就直接在flask的templates中实现vue框架了。

github地址:https://github.com/anRank/flask-vue_curd-.git

二、代码分析
这次还是遇到挺多新问题的,比如js和python的异步问题,导致数据处理中需要添加额外的条件进行控制。还有在视图函数中对sqlite3数据库的一些操作等等等。等再逐步分析一下这些问题吧。

持续逐步更新中~

三、代码

前端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../static/vue.js"></script>
    <script src="../static/axios.min.js"></script>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
</head>
<body>
<div id="app">
    <el-row :gutter="24">
        <el-col :span="10">
            <el-input v-model="searchData" placeholder="请输入内容"></el-input>
        </el-col>
        <el-col :span="2">
            <el-button type="primary" @click="handleSearch()">查询</el-button>
        </el-col>
        <el-col :span="10">
            <el-input v-model="addData" placeholder="请输入内容"></el-input>
        </el-col>
        <el-col :span="2">
            <el-button type="primary" @click="handleAdd">添加</el-button>
        </el-col>
    </el-row>

    <br>

    <template>
        <el-table :data="tableData" border style="width: 100%">
            <el-table-column prop="date" label="日期" width="200">
            </el-table-column>

            <el-table-column prop="mission" label="任务" width="600" >
                <template slot-scope="{row, $index}">
                    <span  v-if="editable[$index]">
                        <el-input v-model="updateData" @blur="saveUpdate($index)"></el-input>
                    </span>
                    <span v-else>
                        ${ tableData[$index].mission }
                    </span>
                </template>
            </el-table-column>

            <el-table-column prop="level" label="等级" width="200">
                <template slot-scope="{row, $index}">
                    <el-button type="text" @click="levelDown($index)">-</el-button>
                    ${ tableData[$index].level }
                    <el-button type="text" @click="levelUp($index)">+</el-button>
                </template>

            </el-table-column>

            <el-table-column fixed="right" label="操作" width="200">
                <template slot-scope="scope">
                    <el-button type="primary" size="small" @click="handleUpdate(scope.$index, tableData)">编辑</el-button>
                    <el-button type="primary" size="small" @click="handleDelete(scope.$index, tableData)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </template>

</div>
</body>
<script>
    var vm = new Vue({
        el: '#app',
        delimiters: ['${', '}'],
        data: {
            searchData: '',
            addData: '',
            updateData: '',
            searchData: '',
            getData: [],
            tableData: [{
                date: '2020-05-12',
                mission: '学习',
                level: "A",
            }],
            editable: [false,],
            levelArr: ['S', 'A', 'B', 'C', 'D'],
            searchResult: [],
            tempData: [],
        },
        methods: {
            handleSearch() {
                if(this.searchData == '') {
                    if (this.tempData != '') {
                        this.tableData = this.tempData;
                        this.tempData = [];
                        this.searchResult = [];
                    }
                }
                else {
                    let search = this.searchData;
                    for(let i=0;i<this.tableData.length;i++) {
                        for(let j=0;j<search.length;j++) {
                            if(this.tableData[i].mission.indexOf(search[j]) > -1) {
                                this.searchResult.push(this.tableData[i]);
                                break;
                            }
                        }
                    }
                    this.tempData = this.tableData;
                    this.searchData = '';
                    this.tableData = this.searchResult;
                }
            },

            handleAdd() {
                var tempData = this.addData;
                this.addData = '';
                var nowDate = new Date().format("yyyy-MM-dd");
                var level = "S";
                var newTable = { date: nowDate, mission: tempData, level: level, editIf: false};
                this.tableData.push(newTable);
                this.editable.push(false);

                axios({
                    url: '/submit',
                    method: 'post',
                    data: {"date": nowDate, "mission": tempData, "level": level}
                }).then((res) => {
                    console.log(res.config.data)
                }).catch((err) => {
                    console.log(err)
                })
            },

            handleDelete(index, rows) {
                let nowDate = this.tableData[index].date
                let tempData = this.tableData[index].mission
                let level = this.tableData[index].level
                axios({
                    url: '/deletedata',
                    method: 'post',
                    data: {"date": nowDate, "mission": tempData, "level": level}
                }).then((res) => {
                    console.log(res.config.data)
                }).catch((err) => {
                    console.log(err)
                })
                rows.splice(index, 1);
            },

            handleUpdate(index, rows) {
                Vue.set(this.editable, index, true);

            },

            saveUpdate(index) {
                let tempData = this.tableData[index].mission;
                this.tableData[index].mission = this.updateData;
                Vue.set(this.editable, index, false);

                let upd = this.updateData;
                this.updateData = '';
                let nowDate = this.tableData[index].date
                let level = this.tableData[index].level
                axios({
                    url: '/update',
                    method: 'post',
                    data: {"date": nowDate, "mission": tempData, "level": level, "new": upd}
                }).then((res) => {
                    console.log(res.config.data)
                }).catch((err) => {
                    console.log(err)
                })
                rows.splice(index, 1);
            },

            levelUp(index) {
                let p;
                for(let i=0;i<5;i++) {
                    if(this.tableData[index].level == this.levelArr[i]) {
                        p = i;
                    }
                }
                if(p!=0){
                    p--;
                    this.tableData[index].level = this.levelArr[p];
                }

            },

            levelDown(index) {
                let p;
                for(let i=0;i<5;i++) {
                    if(this.tableData[index].level == this.levelArr[i]) {
                        p = i;
                    }
                }
                if(p!=4) {
                    p++;
                    this.tableData[index].level = this.levelArr[p];
                }
            },

        },

        created: function () {
        axios({
            url: '/readdata',
            method: 'get'
        }).then((res) => {
            console.log(res)
            let d = res.data
            d = d.replace(/^\s*|\s*$/g,"");
            this.getData = d.split(" ")
            let t = []
            for(let i=0;i<this.getData.length;i++) {
                dic = {"date": this.getData[i], "mission": this.getData[i+1], "level": this.getData[i+2]}
                t.push(dic)
                this.tableData.push(dic)
                i+=2;
            }
        }).catch((err) => {
            console.log(err)
        })
        }
    })

    Date.prototype.format = function(fmt){
        var o = {
            "M+" : this.getMonth()+1,                 //月份
            "d+" : this.getDate(),                    //日
            "h+" : this.getHours(),                   //小时
            "m+" : this.getMinutes(),                 //分
            "s+" : this.getSeconds(),                 //秒
            "q+" : Math.floor((this.getMonth()+3)/3), //季度
            "S"  : this.getMilliseconds()             //毫秒
        };

        if(/(y+)/.test(fmt)){
            fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
        }

        for(var k in o){
            if(new RegExp("("+ k +")").test(fmt)){
                fmt = fmt.replace(
                    RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
            }
        }

        return fmt;
    }
</script>
</html>

后端:

import os
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, render_template, url_for, request, flash
import ast
import json
import sqlite3 as sql


basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)


class Todolist(db.Model):
    __tablename__ = 'todolist'
    id = db.Column(db.Integer, primary_key=True)
    date = db.Column(db.String(64))
    mission = db.Column(db.String(64))
    level = db.Column(db.String(64))

    def __init__(self, date, mission, level):
        self.date = date
        self.mission = mission
        self.level = level

    def __repr__(self):
        return '<Todolist %r>' % self.mission


@app.route('/')
def index():
    return 'Welcome!'


@app.route('/submit', methods=['GET', 'POST'])
def submit():
    if request.method == 'POST':
        data = request.data.decode()
        if data != '':  # 这里有个异步的问题。。
            d = eval(data)
            date = d['date']
            mission = d['mission']
            level = d['level']
            newlist = Todolist(date, mission, level)
            db.session.add(newlist)
            db.session.commit()
        return render_template('index.html')
    else:
        return render_template('index.html')


@app.route('/readdata')
def readdata():
    con = sql.connect("data.sqlite")
    con.row_factory = sql.Row
    cur = con.cursor()
    cursor = cur.execute("select date, mission, level from todolist")
    res = ''
    for row in cursor:
        res = res + ' ' + str(row[0]) + ' ' + str(row[1]) + ' ' + str(row[2])
    return res


@app.route('/deletedata', methods=['GEt', 'POST'])
def deletedata():
    data = request.data.decode()
    if request.method == 'POST':
        if data != '':  # 这里有个异步的问题。。
            d = eval(data)
            date = d['date']
            mission = d['mission']
            level = d['level']
            newlist = Todolist.query.filter_by(date=date, mission=mission, level=level).first()
            db.session.delete(newlist)
            db.session.commit()
            print('ok')
            return render_template('index.html')
    else:
        return render_template('index.html')


@app.route('/update', methods=['GET', 'POST'])
def update():
    data = request.data.decode()
    if request.method == 'POST':
        if data != '':  # 这里有个异步的问题。。
            d = eval(data)
            date = d['date']
            mission = d['mission']
            level = d['level']
            upd = d['new']
            nlist = Todolist.query.filter_by(date=date, mission=mission, level=level).first()
            nlist.mission = upd
            db.session.commit()
            return render_template('index.html')
    else:
        return render_template('index.html')


if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值