Flask+前端+MySQL实现增加、显示用户的功能

html代码

1、显示用户页面代码 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>用户列表</h1>
    <table border="1">
        <thead>
            <tr>
                <th>用户名</th>
                <th>密码</th>
            </tr>
        </thead>

         <tbody>
                {% for item in data_list %}
                    <tr>
                        <td>{{item.user}}</td>
                        <td>{{item.password}}</td>
                    </tr>
                {% endfor %}
         </tbody>
    </table>
</body>
</html>

 2、用户登陆页面代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>添加用户</h1>
    <form method="post" action="/add/user">
        <input type="text" name="user" placeholder="用户名">
        <input type="password" name="pwd" placeholder="密码">
        <input type="submit" value="提交">
    </form>

</body>
</html>

注意:html文件一定要在 templates包下

Python代码

from flask import Flask,render_template,request
import pymysql
app=Flask(__name__)

@app.route("/add/user",methods=["GET","POST"])
def add_user():
    if request.method=="GET":
        return render_template("add_user.html")
    username=request.form.get("user")
    password=request.form.get("pwd")
    # 1、连接数据库
    conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password='123456', charset="utf8", db='itcast')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

    # 2、发送指令,(千万不要用字符串格式化去做字符串的拼接,安全隐患sql注入)
    sql = "insert into laptop(user,password) values(%s,%s)"
    cursor.execute(sql, [username, password])
    conn.commit()
    # 3、关闭连接
    cursor.close()
    conn.close()
    return "添加成功"

@app.route("/show/user")
def show_user():
    conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password='123456', charset="utf8", db='itcast')
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    cursor.execute("select * from laptop")
    data_list = cursor.fetchall()
    conn.commit()
    cursor.close()
    conn.close()
    return render_template("show_user.html",data_list=data_list)

if __name__ == '__main__':
    app.run()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值