用phy写一个增删改查
时间: 2023-12-29 19:59:05 浏览: 64
phy mdio读写源码
这里给您提供一个用 Python 的 Flask 框架实现增删改查的示例代码:
```python
from flask import Flask, request, jsonify
app = Flask(__name__)
# 模拟一个数据库,存储学生信息
students = [
{"id": 1, "name": "Tom", "age": 20},
{"id": 2, "name": "Jerry", "age": 21},
{"id": 3, "name": "Mike", "age": 22}
]
# 查询所有学生信息
@app.route('/students', methods=['GET'])
def get_students():
return jsonify(students)
# 根据 id 查询学生信息
@app.route('/students/<int:student_id>', methods=['GET'])
def get_student(student_id):
for student in students:
if student['id'] == student_id:
return jsonify(student)
return jsonify({"message": "Student not found"})
# 添加学生信息
@app.route('/students', methods=['POST'])
def add_student():
new_student = {
"id": request.json['id'],
"name": request.json['name'],
"age": request.json['age']
}
students.append(new_student)
return jsonify({"message": "Student added successfully"})
# 根据 id 更新学生信息
@app.route('/students/<int:student_id>', methods=['PUT'])
def update_student(student_id):
for student in students:
if student['id'] == student_id:
student['name'] = request.json['name']
student['age'] = request.json['age']
return jsonify({"message": "Student updated successfully"})
return jsonify({"message": "Student not found"})
# 根据 id 删除学生信息
@app.route('/students/<int:student_id>', methods=['DELETE'])
def delete_student(student_id):
for student in students:
if student['id'] == student_id:
students.remove(student)
return jsonify({"message": "Student deleted successfully"})
return jsonify({"message": "Student not found"})
if __name__ == '__main__':
app.run(debug=True)
```
这个示例代码实现了一个简单的增删改查功能,使用 Flask 框架搭建 Web 服务,模拟了一个简单的数据库,包括了查询所有学生信息、根据 id 查询学生信息、添加学生信息、根据 id 更新学生信息、根据 id 删除学生信息等功能。您可以根据自己的需要修改或扩展这个示例代码。
阅读全文