当前位置:   article > 正文

flask-SQLAlchemy-pydantic实现数据校验的增删改查操作_sqlalchemy pydantic

sqlalchemy pydantic
  1. from typing import Optional
  2. from flask import Flask, jsonify, views, request
  3. from flask_sqlalchemy import SQLAlchemy
  4. from flask_pydantic import validate
  5. from pydantic import BaseModel
  6. from demo import Role, to_json
  7. app = Flask(__name__)
  8. # 通过 app 配置数据库信息
  9. app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:149789@127.0.0.1:3306/sqlalchemy_test'
  10. app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
  11. # 创建数据库实例
  12. db = SQLAlchemy(app)
  13. class RolePageModel(BaseModel):
  14. page: Optional[int] = None
  15. size: Optional[int] = None
  16. class RoleCreateModel(BaseModel):
  17. data: str
  18. age: int
  19. class RoleUpdateModel(BaseModel):
  20. id: int
  21. data: Optional[str] = None
  22. age: int
  23. class RoleDeleteModel(BaseModel):
  24. id: int
  25. class RoleView(views.MethodView):
  26. @validate()
  27. def get(self, query: RolePageModel):
  28. # 获取角色列表
  29. page = query.page
  30. size = query.size
  31. if not page:
  32. page = 1
  33. if not size:
  34. size = 2
  35. if size > 2:
  36. size = 2
  37. # 获取角色列表
  38. try:
  39. all_obj = db.session.query(Role).paginate(page, size).items
  40. except Exception:
  41. return jsonify({"status": 404, "msg": "没有内容了"})
  42. ret_json = to_json(all_obj)
  43. return jsonify(ret_json)
  44. @validate()
  45. def post(self, body: RoleCreateModel):
  46. # 创建一个角色
  47. data = body.data
  48. age = body.age
  49. r1 = Role(data=data, age=age)
  50. db.session.add(r1)
  51. db.session.commit()
  52. return jsonify({"code": 201, "msg": "添加成功", "role": r1.to_dict()})
  53. @validate()
  54. def patch(self, query: RoleUpdateModel):
  55. # 更新一个角色
  56. id = query.id
  57. age = query.age
  58. r1 = db.session.query(Role).filter(Role.id == id).first()
  59. if not r1:
  60. return jsonify({"status": 404, "msg": "内容没找到"})
  61. if query.data:
  62. r1.data = query.data
  63. r1.age = age
  64. db.session.commit()
  65. return jsonify({"code": 201, "msg": "更新成功", "role": r1.to_dict()})
  66. @validate()
  67. def delete(self, body: RoleDeleteModel):
  68. # 删除一个角色
  69. # r1 = db.session.query(Role).filter(Role.id == id).first()
  70. id = body.id
  71. # get方法,找不到返回None
  72. r1 = db.session.query(Role).get(id)
  73. if not r1:
  74. return jsonify({"status": 404, "msg": "内容没找到"})
  75. db.session.delete(r1)
  76. db.session.commit()
  77. return jsonify({"code": 204, "msg": "删除成功"})
  78. app.add_url_rule("/role", view_func=RoleView.as_view("role"))
  79. if __name__ == '__main__':
  80. app.run()

flask-pydantic参考链接:https://github.com/bauerji/flask_pydantic 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/521833
推荐阅读
相关标签
  

闽ICP备14008679号