【接口】留言板
2018-04-18 本文已影响0人
一颗老不死的心
- 定义模型
class Message(db.Model):
"""Basic message model
"""
id = db.Column(db.Integer, primary_key=True)
body = db.Column(db.String(200), nullable=False)
create_time = db.Column(db.DateTime, default=db.func.now())
def __init__(self, **kwargs):
super(Message, self).__init__(**kwargs)
def __repr__(self):
return "<Message %d>" % self.id
- 编码接口
class MessageSchema(ma.ModelSchema):
create_time = ma.DateTime(dump_only=True, format='%Y-%m-%d %H:%M:%S')
class Meta:
model = Message
sqla_session = db.session
class MessageResource(Resource):
"""Single object resource
"""
method_decorators = [jwt_required]
def get(self, message_id):
schema = MessageSchema()
message = Message.query.get_or_404(message_id)
return {"message": schema.dump(message).data}
@admin_required
def delete(self, message_id):
message = Message.query.get_or_404(message_id)
db.session.delete(message)
db.session.commit()
return {"msg": "message deleted"}
class MessageList(Resource):
"""Creation and get_all
"""
method_decorators = {
'get': [jwt_required]
}
def get(self):
schema = MessageSchema(many=True)
query = Message.query
return paginate(query, schema)
def post(self):
schema = MessageSchema()
message, errors = schema.load(request.json)
if errors:
return errors, 422
db.session.add(message)
db.session.commit()
return {"msg": "message created", "message": schema.dump(message).data}, 201