Python flask demo

app.py

python 复制代码
from flask import Flask, request, jsonify, render_template
from flask_mysqldb import MySQL

# 初始化 Flask 应用
app = Flask(__name__)

# 配置 MySQL
app.config['MYSQL_HOST'] = 'localhost'  # MySQL 主机地址
app.config['MYSQL_USER'] = 'root'       # MySQL 用户名
app.config['MYSQL_PASSWORD'] = 'admin'  # MySQL 密码
app.config['MYSQL_DB'] = 'py_test'  # 数据库名称
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'  # 返回字典格式的结果

# 初始化 MySQL
mysql = MySQL(app)

# 首页 - 显示所有用户
@app.route('/')
def index():
    cur = mysql.connection.cursor()
    cur.execute("SELECT * FROM users")
    users = cur.fetchall()
    cur.close()
    return render_template('index.html', users=users)

# 添加用户
@app.route('/add', methods=['POST'])
def add_user():
    if request.method == 'POST':
        name = request.form['name']
        email = request.form['email']

        cur = mysql.connection.cursor()
        cur.execute("INSERT INTO users (name, email) VALUES (%s, %s)", (name, email))
        mysql.connection.commit()
        cur.close()

        return jsonify({'message': 'User added successfully!'})

# 更新用户
@app.route('/update/<int:id>', methods=['PUT'])
def update_user(id):
    if request.method == 'PUT':
        data = request.get_json()
        name = data.get('name')
        email = data.get('email')

        cur = mysql.connection.cursor()
        cur.execute("UPDATE users SET name = %s, email = %s WHERE id = %s", (name, email, id))
        mysql.connection.commit()
        cur.close()

        return jsonify({'message': 'User updated successfully!'})

@app.route('/update2',methods=['put'])

    

# 删除用户
@app.route('/delete/<int:id>', methods=['DELETE'])
def delete_user(id):
    cur = mysql.connection.cursor()
    cur.execute("DELETE FROM users WHERE id = %s", (id,))
    mysql.connection.commit()
    cur.close()

    return jsonify({'message': 'User deleted successfully!'})

# 获取单个用户
@app.route('/user/<int:id>', methods=['GET'])
def get_user(id):
    cur = mysql.connection.cursor()
    cur.execute("SELECT * FROM users WHERE id = %s", (id,))
    user = cur.fetchone()
    cur.close()

    if user:
        return jsonify(user)
    else:
        return jsonify({'message': 'User not found'}), 404

# 启动应用
if __name__ == '__main__':
    app.run(debug=True)

index.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Management</title>
</head>
<body>
    <h1>User List</h1>

    <!-- 添加用户表单 -->
    <form id="addUserForm">
        <input type="text" name="name" placeholder="Name" required>
        <input type="email" name="email" placeholder="Email" required>
        <button type="submit">Add User</button>
    </form>

    <!-- 用户列表 -->
    <ul id="userList">
        {% for user in users %}
            <li>
                {{ user.name }} ({{ user.email }})
                <button onclick="deleteUser({{ user.id }})">Delete</button>
            </li>
        {% endfor %}
    </ul>

    <script>
        // 添加用户
        document.getElementById('addUserForm').addEventListener('submit', function (e) {
            e.preventDefault();
            fetch('/add', {
                method: 'POST',
                body: new FormData(this)
            }).then(response => response.json())
              .then(data => {
                  alert(data.message);
                  location.reload(); // 刷新页面
              });
        });

        // 删除用户
        function deleteUser(id) {
            fetch(`/delete/${id}`, {
                method: 'DELETE'
            }).then(response => response.json())
              .then(data => {
                  alert(data.message);
                  location.reload(); // 刷新页面
              });
        }
    </script>
</body>
</html>

效果,浏览器输入:http://127.0.0.1:5000/

相关推荐
wj3055853787 小时前
课程 9:模型测试记录与 Prompt 策略
linux·人工智能·python·comfyui
为何创造硅基生物7 小时前
C语言 结构体内存对齐规则(通俗易懂版)
c语言·开发语言
吃好睡好便好7 小时前
在Matlab中绘制横直方图
开发语言·学习·算法·matlab
星寂樱易李7 小时前
iperf3 + Python-- 网络带宽、网速、网络稳定性
开发语言·网络·python
仰泳之鹅8 小时前
【C语言】自定义数据类型2——联合体与枚举
c语言·开发语言·算法
qingfeng154158 小时前
企业微信机器人开发:如何实现自动化与智能运营?
人工智能·python·机器人·自动化·企业微信
之歆8 小时前
DAY_12JavaScript DOM 完全指南(二):实战与性能篇
开发语言·前端·javascript·ecmascript
cen__y9 小时前
Linux12(Git01)
linux·运维·服务器·c语言·开发语言·git
AI人工智能+电脑小能手9 小时前
【大白话说Java面试题 第65题】【JVM篇】第25题:谈谈对 OOM 的认识
java·开发语言·jvm