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/

相关推荐
2601_962078191 小时前
Python中calendar.weekday用法
python·编程技巧·calendar·日期处理·weekday
2601_962218611 小时前
万象生鲜系统业财一体化底层打通技术自动生成经营账单
大数据·数据库·人工智能·python·算法
2601_966949651 小时前
为什么量化策略需要大量历史股票数据?从回测可信度理解数据规模
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
niucloud-admin1 小时前
JAVA V6 多商户商城 开发文档——插件目录结构
java·开发语言
2601_962885721 小时前
如何用 Python 扫描 A 股跳空缺口并统计缺口回补概率?
java·前端·python
滕州市燕猫虎计算机科技工作室个体工商户2 小时前
Java锁
java·开发语言
李高钢2 小时前
Python FastAPI 框架入门:从零搭建你的第一个高性能 API 服务
数据库·python·fastapi
多加点辣也没关系2 小时前
JavaScript|第31章:表单与控件
开发语言·javascript·ecmascript
菜鸟~noob2332 小时前
【电子战】 第09篇:阵列信号处理——波束形成、MVDR、MUSIC【含matlab代码】
开发语言·matlab·信号处理
ocean21032 小时前
2025-2026年Python面试高频知识点洞察
开发语言·python·面试·python八股文