extentions.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from contextlib import contextmanager
  2. from common.error_types import ApiException
  3. from flask import Flask, jsonify
  4. from flask_cors import CORS
  5. from flask_jwt_extended import JWTManager
  6. from flask_marshmallow import Marshmallow
  7. from flask_migrate import Migrate
  8. from flask_restful import Api as _Api
  9. from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy
  10. from loguru import logger
  11. from werkzeug.exceptions import HTTPException
  12. class Api(_Api):
  13. def handle_error(self, e):
  14. if isinstance(e, ApiException):
  15. code = e.code
  16. msg = e.msg
  17. msgZH = e.msgZH
  18. error_code = e.error_code
  19. elif isinstance(e, HTTPException):
  20. code = e.code
  21. msg = e.description
  22. msgZH = '服务异常,详细信息请查看日志'
  23. error_code = e.code
  24. else:
  25. code = 500
  26. msg = str(e)
  27. error_code = 500
  28. msgZH = '服务异常,详细信息请查看日志'
  29. # 使用 loguru 记录异常信息
  30. logger.opt(exception=e).error(f'An error occurred: {msg}')
  31. return jsonify({
  32. 'error': 'Internal Server Error' if code == 500 else e.name,
  33. 'msg': msg,
  34. 'msgZH': msgZH,
  35. 'code': code,
  36. 'error_code': error_code
  37. }), code
  38. class SQLAlchemy(_SQLAlchemy):
  39. @contextmanager
  40. def auto_commit(self):
  41. try:
  42. yield
  43. db.session.commit()
  44. db.session.flush()
  45. except Exception as e:
  46. db.session.rollback()
  47. raise e
  48. app = Flask(__name__)
  49. CORS(app, supports_credentials=True)
  50. db = SQLAlchemy()
  51. migrate = Migrate()
  52. jwt = JWTManager()
  53. ma = Marshmallow()
  54. folder = app.config.get('REACT_APP_DIST')