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/

相关推荐
iwhitney1 小时前
【次方量化】3分钟搞懂什么是量化策略
python
高洁011 小时前
大模型部署资源不足?轻量化部署解决方案
python·深度学习·机器学习·数据挖掘·transformer
阿里云大数据AI技术1 小时前
MaxFrame 视频帧智能分析:从视频到语义向量的端到端分布式处理
人工智能·python
淘矿人2 小时前
从0到1:用Claude启动你的第一个项目
开发语言·人工智能·git·python·github·php·pygame
cany10002 小时前
C++ -- 模板的声明和定义
开发语言·c++
澈2072 小时前
深耕进阶 Day1:C 与 C++ 核心差异 + C++ 入门基石
c语言·开发语言·c++
嘻嘻哈哈樱桃2 小时前
牛客经典101题题解集--动态规划
java·数据结构·python·算法·职场和发展·动态规划
Felven2 小时前
C. Need More Arrays
c语言·开发语言
gmaajt2 小时前
Golang怎么做国际化多语言_Golang i18n教程【核心】
jvm·数据库·python
love530love2 小时前
Podman Machine 虚拟硬盘迁移实战二:用 Junction 把 vhdx 从 C 盘搬到其他盘
c语言·开发语言·人工智能·windows·wsl·podman·podman machine