ython + Flask + SQLAlchemy 实现一个后端接口,实现一张表的 CRUD具体操作
时间: 2023-06-19 21:06:03 浏览: 113
好的,以下是一个简单的示例:
首先,需要安装 Flask 和 SQLAlchemy:
```python
pip install Flask
pip install SQLAlchemy
```
然后,创建一个 Flask 应用并初始化 SQLAlchemy:
```python
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///example.db'
db = SQLAlchemy(app)
```
接下来,定义一个模型类来映射数据库中的表:
```python
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
age = db.Column(db.Integer)
```
然后,定义一组接口来实现 CRUD 操作:
```python
# 创建用户
@app.route('/users', methods=['POST'])
def create_user():
data = request.json
user = User(name=data['name'], age=data['age'])
db.session.add(user)
db.session.commit()
return jsonify({'msg': 'created', 'id': user.id}), 201
# 获取用户列表
@app.route('/users', methods=['GET'])
def get_users():
users = User.query.all()
return jsonify([{'id': u.id, 'name': u.name, 'age': u.age} for u in users])
# 获取指定用户
@app.route('/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
user = User.query.get_or_404(user_id)
return jsonify({'id': user.id, 'name': user.name, 'age': user.age})
# 更新用户
@app.route('/users/<int:user_id>', methods=['PUT'])
def update_user(user_id):
data = request.json
user = User.query.get_or_404(user_id)
user.name = data['name']
user.age = data['age']
db.session.commit()
return jsonify({'msg': 'updated', 'id': user.id})
# 删除用户
@app.route('/users/<int:user_id>', methods=['DELETE'])
def delete_user(user_id):
user = User.query.get_or_404(user_id)
db.session.delete(user)
db.session.commit()
return jsonify({'msg': 'deleted', 'id': user.id})
```
最后,启动应用:
```python
if __name__ == '__main__':
app.run(debug=True)
```
现在,可以使用 POST、GET、PUT、DELETE 请求来创建、获取、更新和删除用户了。例如:
创建用户:
```
POST /users HTTP/1.1
Content-Type: application/json
{
"name": "Alice",
"age": 20
}
```
获取用户列表:
```
GET /users HTTP/1.1
```
获取指定用户:
```
GET /users/1 HTTP/1.1
```
更新用户:
```
PUT /users/1 HTTP/1.1
Content-Type: application/json
{
"name": "Alice",
"age": 21
}
```
删除用户:
```
DELETE /users/1 HTTP/1.1
```
阅读全文