1. 编写 Model 转 json 工具类 jsonutil.py
from sqlalchemy.ormimport class_mapper
def obj2dict(model):
columns = [c.keyfor cin class_mapper(model.__class__).columns]
return dict((c,getattr(model, c))for cin columns)
排除字段版本:
def obj2dict(model, exclude_columns=None):
if exclude_columnsis None:
exclude_columns = []
columns = [c.keyfor cin class_mapper(model.__class__).columnsif c.keynot in exclude_columns]
return dict((c,getattr(model, c))for cin columns)
2 . 编写 整合db extend.py
from flask_sqlalchemyimport SQLAlchemy
db = SQLAlchemy()
3. 编写 model.py
from extendimport db
class User(db.Model):
__tablename__ ="user"
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
# varchar, null=0
username = db.Column(db.String(100),nullable=False)
password = db.Column(db.String(100),nullable=False)
email = db.Column(db.String(100))
signature = db.Column(db.String(100))
class Article(db.Model):
__tablename__ ="article"
id = db.Column(db.Integer,primary_key=True,autoincrement=True)
title = db.Column(db.String(200),nullable=False)
content = db.Column(db.Text,nullable=False)
# 添加作者的外键
author_id = db.Column(db.Integer, db.ForeignKey("user.id"))
# backref:会自动的给User模型添加一个articles的属性,用来获取文章列表
author = db.relationship("User",backref="articles")
4. 定义 dto 【使用 pydantic】
from typingimport Optional
from pydanticimport BaseModel
class UserModel(BaseModel):
id: Optional[int] =None
username:str
password:str
email: Optional[str] =None
signature: Optional[str] =None
5. 编写 app.py
from flaskimport Flask, jsonify
from flask.viewsimport MethodView
from flask_pydanticimport validate
from jsonutilimport obj2dict
from modelimport *
from modeldtoimport UserModel
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()
@app.route('/')
def hello_world():# put application's code here
return 'Hello World!'
class UserAPI(MethodView):
def get(self,user_id):
users = User.query.all()
return jsonify({'code':"200",'data': [obj2dict(user)for userin users]})
@validate()
def post(self, body: UserModel):
print(body.dict())
user = User(**body.dict())
db.session.add(user)
db.session.commit()
return jsonify(obj2dict(user))
user_view = UserAPI.as_view('user_api')
app.add_url_rule('/users/',defaults={'user_id':None},
view_func=user_view,methods=['GET', ])
app.add_url_rule('/users/',view_func=user_view,methods=['POST', ])
app.add_url_rule('/users/<int:user_id>',view_func=user_view,
methods=['GET','PUT','DELETE'])
if __name__ =='__main__':
app.run(debug=True)
网友评论