1. create flask 项目
pip install flask and then create app.py
2. install serializer package
pip install marshmallow and pip install marshmallow-sqlalchemy and pip install mysqlclient
3. create extend.py
from flask_sqlalchemyimport SQLAlchemy
db = SQLAlchemy()
4. create model.py
from extendimport db
class Book(db.Model):
_tablename__ ="books"
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
code = db.Column(db.String(5))
number = db.Column(db.Integer)
name = db.Column(db.String(50))
createTime = db.Column(db.DateTime,server_default=db.FetchedValue())
5. create serializer.py
from marshmallowimport EXCLUDE, fields
from marshmallow_sqlalchemyimport SQLAlchemyAutoSchema
from modelimport Book
# SQLAlchemyAutoSchema 会自动映射数据库列和字段
class BookSerializer(SQLAlchemyAutoSchema):
number = fields.Str()# 自定义映射类型 num是int类型序列化成string
class Meta:
model = Book# 模型类
ordered =True # 是否排序
include_fk =True # 是否包含外键
unknown = EXCLUDE# 未知字段序列化选项
exclude = ("name",)# 序列化不需要的字段 反之对应include
6. create app.py
from flaskimport views, jsonify, Flask
from extendimport db
from modelimport Book
from serializerimport BookSerializer
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] ='mysql://root:123456@127.0.0.1:3306/sqlalchemy_test'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] =True
db.init_app(app)
with app.app_context():
db.create_all()
class BookViews(views.MethodView):
def get(self, book_id):
try:
if book_idis None:
book = Book.query.all()
resp_data = BookSerializer().dump(book,many=True)
else:
book = Book.query.filter(Book.id == book_id).first()
resp_data = BookSerializer().dump(book)
return jsonify(code=0,success=True,msg=None,data=resp_data)
except Exception as e:
return jsonify(code=1,success=False,msg=str(e),data=None)
book_view = BookViews.as_view('book_api')
app.add_url_rule('/books/',defaults={'book_id':None},view_func=book_view,methods=['GET', ])
app.add_url_rule('/books/<int:book_id>',view_func=book_view,methods=['GET', ])
if __name__ =='__main__':
app.run(debug=True)
开发 rest api demo, marshmallow 还支持validator
网友评论