序列化和反序列化,支持 JSON、YAML 和 XML 等 https://github.com/marshmallow-code/flask-marshmallow
天问 5dea7d38cb Update 'README.md' | 9 months ago | |
---|---|---|
README.md | 9 months ago |
序列化和反序列化,支持 JSON、YAML 和 XML 等
from flask import Flask, request, jsonify
from flask_marshmallow import Marshmallow
app = Flask(__name__)
ma = Marshmallow(app)
# 定义数据模型类
class User:
def __init__(self, id, username, email):
self.id = id
self.username = username
self.email = email
# 定义序列化器类
class UserSchema(ma.Schema):
class Meta:
fields = ('id', 'username', 'email')
# 创建用户数据
users_data = [
User(id=1, username='john_doe', email='john@example.com'),
User(id=2, username='jane_doe', email='jane@example.com')
]
# 创建用户数据模式实例
user_schema = UserSchema()
users_schema = UserSchema(many=True)
# 路由处理函数:获取所有用户数据
@app.route('/users', methods=['GET'])
def get_users():
return jsonify(users_schema.dump(users_data))
# 路由处理函数:创建新用户数据
@app.route('/user', methods=['POST'])
def create_user():
new_user = User(id=request.json['id'], username=request.json['username'], email=request.json['email'])
users_data.append(new_user)
return user_schema.jsonify(new_user)
if __name__ == '__main__':
app.run(debug=True)