Python-web项目基于基于flask框架

 

知识点:

参考链接:

https://www.cnblogs.com/lwn-blog/p/9191388.html

https://zhuanlan.zhihu.com/p/23605789

https://www.cnblogs.com/xp-thebest/p/14311174.html

 

 

 

 

 

 

 

 

代码如下:

addbook.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>新增书籍</small>
                </h1>
            </div>
        </div>
    </div>
    <form action="/addBook" method="POST">
        <div class="form-group">
            <label for="bkname">书籍名称:</label>
            <input type="text" class="form-control" id="bkname" name="bookName" required>
        </div>
        <div class="form-group">
            <label for="bcount">书籍数量:</label>
            <input type="text" class="form-control" id="bcount" name="bookCounts" required>
        </div>
        <div class="form-group">
            <label for="bdetail">书籍描述:</label>
            <input type="text" class="form-control" id="bdetail" name="detail" required>
        </div>
        <div class="form-group">
            <input type="submit" onclick="alert('成功')" class="form-control" value="添加">
        </div>
    </form>
</div>
</body>
</html>

allbook.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>书籍列表 显示所有书籍</small>
                </h1>
            </div>
        </div>
        <div class="row">
            <div class="col-md-4 column">
                <a class="btn btn-primary" href="{{url_for('toaddBook')}}">新增书籍</a>
                <a class="btn btn-primary" href="allBook.html">显示全部书籍</a>
            </div>
            <div class="col-md-8 column">
                <form  class="form-inline" action="/queryBook" method="post" style="float: right">
                    <input type="text" name="queryBookName" class="form-control" placeholder="请输入要查询的书籍名称">
                    <input type="submit" value="查询" class="btn btn-primary">
                </form>
            </div>
        </div>
    </div>

    <div class="row clearfix">
        <div class="col-md-12 column" id="show">

        </div>

    </div>
</div>
</body>
<script>
    $(function () {
        $.ajax({
            url: '{{url_for("getAll")}}',
            async:false,
            type:"POST",
            cache:false,
            dataType:"json",
            success:function (data) {
                var text = "<table class='table table-hover table-striped'>"+
                        "<thead>" +
                        "<tr>" +
                        "<th>书籍编号</th>"+
                        "<th>书籍名称</th>"+
                        "<th>书籍数量</th>"+
                        "<th>书籍详情</th>"+
                        "<th>操作</th>"+
                        "</tr>"+
                        "</thead>"+
                        "<tbody>";
                for (var i=0;i<data.length;i++)
                {
                    var id = data[i].bookID;
                    text+="<tr>"+
                            "<td>"+data[i].bookID+"</td>"+
                            "<td>"+data[i].bookName+"</td>"+
                            "<td>"+data[i].bookCounts+"</td>"+
                            "<td>"+data[i].detail+"</td>"+
                            "<td>" +
                            "<a href='{{url_for('toUpdateBook')}}?"+data[i].bookID+"'>修改</a>"+
                            "<a onclick='deleteBook("+data[i].bookID+")'>删除</a>" +
                            "</td>"+
                            "</tr>";
                }
                text+="<tbody></table>";
                $("#show").html(text);
            },
            error: function (xhr, textStatus, errorThrown) {
           alert("状态码:"+xhr.status);        
           alert("请求失败");
            }
        })
    });

    function deleteBook(bookID) {
        $.ajax({
            url: '{{url_for("deleteBook")}}',
            async:false,
            data:{"bookID":bookID},
            type:"POST",
            cache:false,
            dataType:"text",
            success:function (data) {
                if (data=="yes"){
                    alert("删除成功");
                    location.reload();
                }
            },
            error:function () {
                alert("删除失败");
            }
        })
    }
</script>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <div id="show"></div>
</body>
<script>
    $(function () {
        $.ajax({
            url: '{{url_for("getAll2")}}',
            async:false,
            type:"POST",
            cache:false,
            dataType:"json",
            success:function (data) {
                var text = "<table class='table table-striped'>"+
                        "<thead>" +
                        "<tr>" +
                        "<th>用户名</th>"+
                        "<th>密码</th>"+
                        "<th>手机号码</th>"+
                        "</tr>"+
                        "</thead>"+
                        "<tbody>";
                for (var i=0;i<data.length;i++)
                {
                    text+="<tr>"+
                            "<td>"+data[i].username+"</td>"+
                            "<td>"+data[i].password+"</td>"+
                            "<td>"+data[i].tellphone+"</td>"+
                            "</tr>";
                }
                text+="<tbody></table>";
                $("#show").html(text);
            },
            error: function (xhr, textStatus, errorThrown) {
           alert("状态码:"+xhr.status);        
           alert("请求失败");
            }
        })
    })
</script>
</html>

querybook.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <table class="table table-hover table-striped">
        <thead>
        <tr>
            {% for key, value in result.items() %}
               <th> {{ key }} </th>
            {% endfor %}
        </tr>
        </thead>
        <tbody>
        <tr>
            {% for key, value in result.items() %}
               <td> {{ value }} </td>
            {% endfor %}
        </tr>
        </tbody>
    </table>
</body>
</html>

updatebook.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row clearfix">
        <div class="col-md-12 column">
            <div class="page-header">
                <h1>
                    <small>新增书籍</small>
                </h1>
            </div>
        </div>
    </div>
    <form action="/updateBook" method="POST">
        <input type="hidden" name="bookID" value="{{jsonData.bookID}}">
        <div class="form-group">
            <label for="bkname">书籍名称:</label>
            <input type="text" class="form-control" id="bkname" name="bookName" value="{{jsonData.bookName}}" >
        </div>
        <div class="form-group">
            <label for="bcount">书籍数量:</label>
            <input type="text" class="form-control" id="bcount" name="bookCounts" value="{{jsonData.bookCounts}}">
        </div>
        <div class="form-group">
            <label for="bdetail">书籍描述:</label>
            <input type="text" class="form-control" id="bdetail" name="detail" value="{{jsonData.detail}}">
        </div>
        <div class="form-group">
            <input type="submit" class="form-control" onclick="alert('修改成功')" value="修改">
        </div>
    </form>
</div>
</body>
</html>

app.py

from flask import Flask, request, render_template, redirect, url_for
import pymysql
import json

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('allBook.html')

@app.route('/getAll',methods=['POST','GET'])
def getAll():
    try:
        contect = getConnect()
        cur = contect.cursor()
        cur.execute("select * from books")
        jsonData = []
        for row in cur.fetchall():
            result = {}
            result['bookID'] = row[0]
            result['bookName'] = row[1]
            result['bookCounts'] = row[2]
            result['detail'] = row[3]
            jsonData.append(result)
        return json.dumps(jsonData)
    except Exception as e:
        print("失败", e)
    finally:
        cur.close()
        contect.close()


@app.route('/deleteBook',methods=['POST','GET'])
def deleteBook():
    BookID = request.form['bookID']
    try:
        contect = getConnect()
        mycursor = contect.cursor()
        mycursor.execute("delete from books where bookID = "+BookID)
        contect.commit()
        return "yes"
    except Exception as e:
        print("失败", e)
    finally:
        mycursor.close()
        contect.close()

@app.route('/addBook',methods=['POST','GET'])
def addBook():
    bookName  = request.form['bookName']
    bookCounts = request.form['bookCounts']
    detail = request.form['detail']
    try:
        contect = getConnect()
        mycursor = contect.cursor()
        sql = "insert into books (bookName, bookCounts, detail) values ("+str(bookName)+","+bookCounts+","+str(detail)+")"
        print(sql)
        mycursor.execute(sql)
        contect.commit()
        return render_template("allBook.html")
    except Exception as e:
        print("失败", e)
    finally:
        mycursor.close()
        contect.close()

@app.route("/toaddBook")
def toaddBook():
    return render_template('addBook.html')

@app.route("/toUpdateBook")
def toUpdateBook():
    try:
        bookID = request.url.split("?")[1]
        contect = getConnect()
        mycursor = contect.cursor()
        sql = "select * from books where bookID = " + bookID
        mycursor.execute(sql)
        jsonData = []
        row = mycursor.fetchone()
        result = {}
        result['bookID'] = row[0]
        result['bookName'] = row[1]
        result['bookCounts'] = row[2]
        result['detail'] = row[3]
        return render_template('updateBook.html',jsonData = result)
    except Exception as e:
        print("失败", e)
    finally:
        mycursor.close()
        contect.close()

@app.route('/updateBook',methods=['POST','GET'])
def updateBook():
    bookID = request.form['bookID']
    bookName  = request.form['bookName']
    bookCounts = request.form['bookCounts']
    detail = request.form['detail']
    try:
        contect = getConnect()
        mycursor = contect.cursor()
        sql = "update books set bookName='"+str(bookName)+"',bookCounts='"+bookCounts+"',detail='"+str(detail)+"' where bookID="+ bookID
        print(sql)
        mycursor.execute(sql)
        contect.commit()
        return render_template("allBook.html")
    except Exception as e:
        print("失败", e)
    finally:
        mycursor.close()
        contect.close()

@app.route("/queryBook",methods=['POST','GET'])
def queryBook():
    try:
        bookName = request.form['queryBookName']
        contect = getConnect()
        mycursor = contect.cursor()
        sql = "select * from books where bookName like " + "'%"+bookName+"%'"
        print(sql)
        mycursor.execute(sql)
        jsonData = []
        row = mycursor.fetchone()
        result = {}
        result['bookID'] = row[0]
        result['bookName'] = row[1]
        result['bookCounts'] = row[2]
        result['detail'] = row[3]
        return render_template("queryBook.html",result =result)

    except Exception as e:
        print("失败", e)
    finally:
        mycursor.close()
        contect.close()




def getConnect():
    return pymysql.Connect(host='localhost',port=3306,user="root",passwd="511924..",db="ssmbuild",charset="utf8")

if __name__ == '__main__':
    app.run(debug=True,port=8033)

 

posted @ 2021-01-25 14:50  喜欢爬的孩子  阅读(229)  评论(0编辑  收藏  举报