init_sqlalhemy.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import datetime
  2. import os
  3. from flask import Flask, request
  4. from flask_sqlalchemy import SQLAlchemy
  5. from flask_sqlalchemy.query import Query as BaseQuery
  6. from flask_marshmallow import Marshmallow
  7. from marshmallow import fields
  8. from marshmallow.validate import (
  9. URL, Email, Range, Length, Equal, Regexp,
  10. Predicate, NoneOf, OneOf, ContainsOnly
  11. )
  12. from flask_migrate import Migrate
  13. class Query(BaseQuery):
  14. def soft_delete(self):
  15. return self.update({"delete_at": datetime.datetime.now()})
  16. def logic_all(self):
  17. return self.filter_by(delete_at=None).all()
  18. def all_json(self, schema: Marshmallow().Schema):
  19. return schema(many=True).dump(self.all())
  20. def layui_paginate(self):
  21. return self.paginate(page=request.args.get('page', type=int),
  22. per_page=request.args.get('limit', type=int),
  23. error_out=False)
  24. def layui_paginate_json(self, schema: Marshmallow().Schema):
  25. """
  26. 返回dict
  27. """
  28. _res = self.paginate(
  29. page=request.args.get('page', type=int),
  30. per_page=request.args.get('limit', type=int),
  31. error_out=False
  32. )
  33. return schema(many=True).dump(_res.items), _res.total, _res.page, _res.per_page
  34. def layui_paginate_db_json(self):
  35. """
  36. db.query(A.name).layui_paginate_db_json()
  37. """
  38. _res = self.paginate(page=request.args.get('page', type=int),
  39. per_page=request.args.get('limit', type=int),
  40. error_out=False)
  41. return [dict(i) for i in _res.items], _res.total
  42. db = SQLAlchemy(query_class=Query)
  43. ma = Marshmallow()
  44. migrate = Migrate()
  45. def init_databases(app: Flask):
  46. db.init_app(app)
  47. # db.create_all(app=app)
  48. ma.init_app(app)
  49. if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
  50. with app.app_context():
  51. try:
  52. db.engine.connect()
  53. # 导入sql
  54. # with app.open_resource('schema.sql', mode='r') as f:
  55. # db.cursor().executescript(f.read())
  56. # db.commit()
  57. except Exception as e:
  58. exit(f"数据库连接失败: {e}")