基于python Flask框架+jquery Ajax技术的增删改查(CRUD)

Falsk框架优势:

1.轻巧
2.简洁
3.扩展性强(个人认为最重要的特点)
4.核心(werkzeug和jinja2)jinja2就是指模板引擎。

非常适用于小型网站
非常适用于开发web服务的API
开发大型网站无压力,但代码架构需要自己设计,开发成本取决于开发者的能力和经验
各方面性能均等于或优于Django
Django自带的或第三方的好评如潮的功能,Flask上总会找到与之类似第三方库
Flask灵活开发,Python高手基本都会喜欢Flask,但对Django却可能褒贬不一
Flask与关系型数据库的配合使用不弱于Django,而其与NoSQL数据库的配合远远优于Django
Flask比Django更加Pythonic,与Python的philosophy更加吻合

如下是对单表增删改查的具体实例

注:本篇文章是在上篇文章的基础上进行的更改,因为在已有的后台处理上,对不同的数据表的数据处理其实就是sql语句的不同以及封装数据还有前台js中的ajax略有差异,方法名称没有太大改变,但是本篇文章在原来的基础上又在后面新增加了一个bootstrap的模态框用于实现增加数据的操作;具体代码实现如下(文件目录结构与上片大体一致):

shopcontroller.py文件:

from flask import render_template, Blueprint, request
from service.shopservice import ShopService
from entity.shop import Shop
import json

shopcontroller = Blueprint('shopcontroller',__name__)
shopService=ShopService()

#删除功能
@shopcontroller.route('/removeshop.do',methods = ['POST','GET'])
def goRemoveShop():
    shopId = request.args.get('shopId')
    job_city = request.form.get('job_city')
  

    shop = Shop()
    shop.job_position = job_city
    result = shopService.removeShop(shopId)
    shopList = shopService.findPageShopList(shop,16,1)
    return render_template('systeminfo/messageinfo.html',shopList = shopList,message="删除成功" if result>0 else "删除失败")  #前端用的key

#确认修改
@shopcontroller.route('/checkshopname.do',methods = ['POST','GET'])
def checkShopName():
    shopdata = request.get_data()
    shopDict = json.loads(shopdata)
    shop = Shop()
    shop.job_id = shopDict.get('shopId')   #将数据赋给user实体的属性
    shop.job_position=shopDict.get('shopName')
    shop.job_MMoney = shopDict.get('shopPrice')
    shop.job_city = shopDict.get('shopNum')

    result =shopService.updateShop(shop)

    dicts={}
    if result:
        dicts = {'code':1}
    else:
        dicts = {'code':0}

    return json.dumps(dicts)
    pass

#查询以及分页
@shopcontroller.route('/ajaxshopinfo.do', methods=['POST', 'GET'])
def getShopInfo():
    shopData = request.get_data()
    shopDict = json.loads(shopData)
    tData = {}

    shop = Shop()
    shop.job_city = shopDict.get('shopName')
    currentPage = int(shopDict.get('currentPage'))
    pageSize = int(shopDict.get('pageSize'))
    opr = shopDict.get('opr')
    shopId = shopDict.get('shopId')
    shop.job_id = shopId

    result = shopService.findPageShopList(shop, pageSize, currentPage)
    counts = shopService.countShops(shop)
    totalPage = 0

    if(counts%pageSize == 0):
        totalPage = counts//pageSize
    else:
        totalPage = counts // pageSize + 1
        pass

    returnData = {'code':1, 'shopData':result, 'pageSize':pageSize, 'currentPage':currentPage, 'totalPage':totalPage, 'opr':'search'}

    return json.dumps(returnData)
    pass

#确认添加
@shopcontroller.route('/submits.do', methods=['POST', 'GET'])
def submits():
    Text = request.get_data()
    TextDict = json.loads(Text)

    shop = Shop()
    shop.job_position = TextDict.get('jobposition')
    shop.job_MMoney = TextDict.get('jobmoney')
    shop.job_city= TextDict.get('jobcity')


    result = shopService.submits(shop)
    print(result)

    dicts = {}
    if result:
        dicts = {'code': 1}
    else:
        dicts = {'code': 0}

    return json.dumps(dicts)

    pass

basedao.py(连接数据库以及提供通用的数据库接口文件)

import pymysql
import json
import os
#DBUtils.py
class BaseDao():
    def __init__(self,configPath = 'pymysql.json'):
        self.__connection =None
        self.__cursor = None
        self.__config = json.load(open(os.path.dirname(__file__) + os.sep + configPath,'r')) #通过json配置获得数据的连接配置信息
        print(self.__config)
        pass
    def getConnection(self):
        #当有连接对象时,直接返回连接对象
        if self.__connection:
            return self.__connection
        #否则通过建立新的连接对象
        try:
            self.__connection = pymysql.connect(**self.__config)
            return self.__connection
        except pymysql.MySQLError as e:
            print("Exception"+str(e))
        pass
    pass
    #用于执行Sql语句的通用方法
    def execute(self,sql,params=None):
        try:
            self.__cursor = self.getConnection().cursor()
            #execute:返回的是修改数据的条数
            if params:
                result = self.__cursor.execute(sql,params)
            else:
                result = self.__cursor.execute(sql)
            return result
        except (pymysql.MySQLError,pymysql.DatabaseError,Exception) as e:#捕获多个异常
            print("出现数据库访问异常:"+str(e))
            self.rollback()
            pass
        pass
    pass
    def fetch(self):
        if self.__cursor:     #提高代码健壮性
            return self.__cursor.fetchall()
        pass

    def fetchOne(self):
        if self.__cursor:     #提高代码健壮性
            return self.__cursor.fetchone()
        pass

    def commit(self):
        if self.__connection:
            self.__connection.commit()    #回滚问题
        pass

    def rollback(self):
        if self.__connection:
            self.__connection.rollback()

        pass

    def getLastRowId(self):
        if self.__cursor:
            return self.__cursor.lastrowid

    def close(self):
        if self.__cursor:
            self.__cursor.close()
        if self.__connection:
            self.__connection.close()
    pass

if __name__=="__main__":
    ms = BaseDao()

pymysql.json(数据库信息配置文件)

{"host":"127.0.0.1","user":"root","password":"root", "database" :"你的数据库","port":你的数据库密码}

shopdao.py文件

from .basedao import BaseDao

class ShopDao(BaseDao):

    #删除功能的函数
    def removeShop(self,shopId):
        try:
            sql = "delete from job_position where job_id=%s"
            self.getConnection()
            result = self.execute(sql, (shopId,))
            self.commit()  # 执行语句后要提交
        finally:
            self.close()
        return result
        pass

    #修改数据库数据
    def updateShop(self,shop):
        try:
            sql = "update job_position set job_city=%s,job_MMoney=%s,jobposition=%s where job_id=%s"
            self.getConnection()
            result = self.execute(sql,(shop.job_city,shop.job_MMoney,shop.job_position,shop.job_id))
            self.commit()  # 执行语句后要提交
        finally:
            self.close()
        return result
        pass

    #支持查询分页
    def findPageShopList(self, shop, pageSize, currentPage):
        try:
            params = []
            # sql语句和param就需要是动态
            sql = "select * from job_position where 1=1 "  # where 1=1 便于增加and
            if shop.job_city:
                sql += " and job_city like %s "
                params.append('%' + shop.job_city + '%')  # 支持模糊查询
                pass


            startRow = (currentPage - 1) * pageSize

            sql += "limit %s, %s"
            params.append(startRow)
            params.append(pageSize)

            self.getConnection()
            self.execute(sql, params)
            result = self.fetch()
        finally:
            self.close()

        return result
        pass

    def countShops(self, shop):
        params = []
        # sql语句和params就需要是动态
        sql = "select count(*) from job_position where 1=1 "  # where 1=1是为了便于增加and
        if shop.job_city:
            sql += " and job_city like %s "  # 模糊查询
            params.append('%' + shop.job_city + '%')
            pass


        self.getConnection()
        self.execute(sql, params)
        result = self.fetchOne()
        return result
        pass

    pass

    def submits(self,shop):
        try:
            sql = "insert into job_position(job_city,job_MMoney,jobposition) values(%s,%s,%s)"
            self.getConnection()
            result = self.execute(sql,(shop.job_city,shop.job_MMoney,shop.job_position))
            self.commit()  #执行语句后要提交
        finally:
            self.close()
        return result

        pass

shop.py文件(初始化职位实体属性文件)

class Shop():
    def __init__(self):
        self.__job_id = None
        self.__job_position = None
        self.__job_MMoney = None
        self.__job_city = None


    @property
    def job_id(self):
        return self.__job_id

    @job_id.setter
    def job_id(self, job_id):
        self.__job_id = job_id

    @property
    def job_position(self):
        return self.__job_position

    @job_position.setter
    def job_position(self, job_position):
        self.__job_position = job_position

    @property
    def job_MMoney(self):
        return self.__job_MMoney

    @job_MMoney.setter
    def job_MMoney(self, job_MMoney):
        self.__job_MMoney = job_MMoney

    @property
    def job_city(self):
        return self.__job_city

    @job_city.setter
    def job_city(self, job_city):
        self.__job_city = job_city

shopservice.py文件

from dao.shopdao import ShopDao
from entity.shop import Shop

class ShopService():

    #删除 id
    def removeShop(self,shopId):
        shopDao = ShopDao()
        return shopDao.removeShop(shopId)
        pass

    #修改
    def updateShop(self,shop):
        shopDao = ShopDao()
        return shopDao.updateShop(shop)  #对数据库进行更新操作

    #分页以及查询
    def findPageShopList(self, shop, pageSize, currentPage):
        shopDao = ShopDao()
        return shopDao.findPageShopList(shop,pageSize,currentPage)
        pass
    #计算用户个数
    def countShops(self, shop):
        shopDao = ShopDao()
        return shopDao.countShops(shop)[0]
        pass
    #确认添加
    def submits(self,shop):
        shopDao = ShopDao()
        return shopDao.submits(shop)
        pass

shop.js文件

//删除
function submitRemoveShop(shopId) {
    if(confirm("确定要删除吗?")){
        window.location.href="/removeshop.do?shopId="+shopId
    }

}

//修改
function submitModifyShop(id) {
    //console.log('#list-line' + id +" td")

    $('#list-lines' + id +" td").attr('contentEditable',true);

// $('#id').attr("readonly","readonly");
}

//点击修改完成按钮的功能,动态将修改的数据控制层(usercontroller.py文件)
function submitModifyShops(id){
    $.ajax({
    type: 'post',                            // 传数据的方式
    url: '/checkshopname.do',
    dataType: 'json',                        // xml、json、script、html
    data:JSON.stringify({
        'shopId': $("td[name='shopId"+id+"']").html(),     //  $('#userName') == document.getElementById('userName')
        'shopName': $("td[name='shopName"+id+"']").html(),
        'shopPrice': $("td[name='shopPrice"+id+"']").html(),
        'shopNum': $("td[name='shopNum"+id+"']").html(),


    }),
    error: function(xhr, err){
        alert('请求失败,请检查,' + err + '!')
    },
    success: function(data, textStatus){    // success对应的回调函数的第一个参数,是服务器返回的数据
        if(data.code==1){
            alert("修改完成!")
            //console.log("成功")
            $('#list-lines' + id +" td").attr('contentEditable',false)

        }
    }
});

}



function getShopData(currentPage, pageSize, opr, shopId) {

    shopName =  document.searchForms.shopName.value


    if(opr == 'del'){
        if(!confirm('确定要删除吗?')){
            return false
        }
    }

    $.ajax({
        type: 'post',                            // 传数据的方式
        url: '/ajaxshopinfo.do',
        dataType: 'json',                        // xml、json、script、html
        data:JSON.stringify({
            'shopId':shopId,
            'shopName':shopName,
            'pageSize': pageSize,
            'currentPage': currentPage,
            'opr': opr
        }),
        error: function(xhr, err){
            alert('请求失败,请检查,' + err + '!')
        },
        success: function(data, textStatus){    // success对应的回调函数的第一个参数,是服务器返回的数据
            if(data.code == 1 && opr != 'update'){
                var htmlTexts = ""
                for(var i =0;i \n' +
                    '                                        \n' +
                    '                                        '+ data.shopData[i][0] +'\n' +
                    '                                        '+ data.shopData[i][1] +'\n' +
                    '                                        '+ data.shopData[i][4] +'\n' +
                    '                                        '+ data.shopData[i][12] +'\n' +
                    '                                        \n' +
                    '                                            删除  \n' +
                    '                                            修改  \n' +
                    '                                            完成\n' +
                    '                                        \n' +
                    '                                        \n' +
                    '                                    '
                }
                pageTexts = '---------------------------------------------------------------------------------------------------' +
                ''+ '当前第' + data.currentPage + '页  总共有' + data.totalPage + '页  ';
                if(data.currentPage <= 1) {
                    pageTexts += '首页   上一页  ';
                }else{
                     pageTexts += '首页   ' +
                        '上一页  ';
                }

                if(data.currentPage >= data.totalPage){
                     pageTexts += '下一页  尾页  ';
                }else {
                    pageTexts += '下一页  ' +
                    '尾页  ';
                }
                pageTexts +=''

                $('#shopDataBody').empty()
                $('#shopDataBody').append(htmlTexts)
                $('#shopDataBody').append(pageTexts)

                document.searchForm.currentPage.value = data.currentPage
                document.searchForm.pageSize.value=data.pageSize
            }

        }
    });
}
$(document).ready(
    function(){
        getShopData(1, 16, 'search', 0)
    }
)

function insert() {
    template = document.getElementById("theTemplate").innerHTML ;
    // console.log(template)//获取index.html界面模态框代码
    $('#model').append(template);
}

function submits(){
    jobposition = $("input[name='jobposition']:first").val()
    jobmoney = $("input[name='jobmoney']:first").val()
    jobcity = $("input[name='jobcity']:first").val()

    $.ajax({
        type: 'post',                            // 传数据的方式
        url: '/submits.do',
        dataType: 'json',                        // xml、json、script、html
        data: JSON.stringify({
            'jobposition':jobposition,
            'jobmoney':jobmoney,
            'jobcity':jobcity,

        }),
        error: function (xhr, err) {
            alert('请求失败,请检查,' + err + '!')
        },
        success: function (data, textStatus) {
            if(data.code==1){
                alert("数据写入成功")
            }
        }
    })


}

messageinfo.html文件(管理员界面)




    
    后台管理界面
    
    
    

    

    






    

管理员界面




城市名:
{# {% for shop in shopList %}#} {# #} {# #} {# #} {# #} {# #} {# #} {# #} {# #} {# #} {# #} {# {% endfor %}#}
职位编号 职位名 月薪 城市
{{ shop.shopId }}{{ shop.shopName }}{{ shop.shopPrice }}{{ shop.shopNum }}{{ shop.shopClassfiy }}{{ shop.shopImgUrl }}#} {# 删除  #} {# 修改  #} {# 完成#} {#
{# 第二块结尾 #}


用户名:
订单编号 用户编号 商品名 购买数量 金额 发件人地址 收件人姓名 收件人电话 收件人地址 操作
{# 第三块结尾#}

销量界面暂未开发

app.py文件(启动程序)

from flask import Flask,render_template,request,session,Response

from controller.shopcontroller import shopcontroller

from datetime import timedelta

app = Flask(__name__)
app.config['DEBUG']=True
app.config['SECRET_KEY'] ="fggggjjjhgggg"
app.config['PERMANENT_SESSION_LIFETIME']=timedelta(minutes=30)



app.register_blueprint(shopcontroller)  #数据层


@app.route('/',methods =['POST','GET'])
def index():
    return render_template('systeminfo/messageinfo.html')


if __name__ == '__main__':
    app.run(host="10.0.14.107",port=8080)

至此,是本文章的全部代码内容,如下图是增加功能的模态框界面效果:
基于python Flask框架+jquery Ajax技术的增删改查(CRUD)_第1张图片
下篇文章见!!!

你可能感兴趣的:(基于python Flask框架+jquery Ajax技术的增删改查(CRUD))