__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. import logging
  2. import os
  3. import uuid
  4. from flask import Flask, jsonify
  5. from flask_cors import CORS
  6. from flask_sqlalchemy import SQLAlchemy
  7. from app.config.config import (
  8. apply_runtime_env_config,
  9. config,
  10. current_env,
  11. log_llm_env_status,
  12. log_service_env_status,
  13. )
  14. from app.config.cors import CORS_OPTIONS
  15. db = SQLAlchemy()
  16. def create_app():
  17. """Create and configure the Flask application"""
  18. app = Flask(__name__)
  19. # 加载配置
  20. app.config.from_object(config[current_env])
  21. apply_runtime_env_config(app)
  22. # 初始化扩展
  23. # 配置CORS以解决跨域问题
  24. CORS(app, **CORS_OPTIONS)
  25. db.init_app(app)
  26. # 注册蓝图
  27. from app.api.business_domain import bp as business_domain_bp
  28. from app.api.data_development import bp as data_development_bp
  29. from app.api.data_factory import bp as data_factory_bp
  30. from app.api.data_flow import bp as data_flow_bp
  31. from app.api.data_interface import bp as data_interface_bp
  32. from app.api.data_rules import bp as data_rules_bp
  33. from app.api.data_service import bp as data_service_bp
  34. from app.api.data_source import bp as data_source_bp
  35. from app.api.graph import bp as graph_bp
  36. from app.api.knowledge_base import bp as knowledge_base_bp
  37. from app.api.meta_data import bp as meta_bp
  38. from app.api.system import bp as system_bp
  39. app.register_blueprint(meta_bp, url_prefix="/api/meta")
  40. app.register_blueprint(data_interface_bp, url_prefix="/api/interface")
  41. app.register_blueprint(data_rules_bp, url_prefix="/api/rules")
  42. app.register_blueprint(graph_bp, url_prefix="/api/graph")
  43. app.register_blueprint(system_bp, url_prefix="/api/system")
  44. app.register_blueprint(data_source_bp, url_prefix="/api/datasource")
  45. app.register_blueprint(data_development_bp, url_prefix="/api/development/v1")
  46. app.register_blueprint(data_flow_bp, url_prefix="/api/dataflow")
  47. app.register_blueprint(business_domain_bp, url_prefix="/api/bd")
  48. app.register_blueprint(data_factory_bp, url_prefix="/api/datafactory")
  49. app.register_blueprint(data_service_bp, url_prefix="/api/dataservice")
  50. app.register_blueprint(knowledge_base_bp, url_prefix="/api/knowledge")
  51. from app.core.system.permissions import configure_api_authorization
  52. configure_api_authorization(app)
  53. # Configure global response headers
  54. configure_response_headers(app)
  55. # Configure logging
  56. configure_logging(app)
  57. log_llm_env_status(app)
  58. log_service_env_status(app)
  59. # 添加全局异常处理器
  60. configure_error_handlers(app)
  61. # 输出启动信息(生产环境由 Gunicorn 按 LISTEN_PORT 监听,此处 PORT 与配置一致)
  62. port = app.config["PORT"]
  63. app.logger.info(
  64. f"Starting server in {current_env} mode on port {port} "
  65. f"(LISTEN_PORT={os.environ.get('LISTEN_PORT', port)})"
  66. )
  67. return app
  68. def configure_response_headers(app):
  69. """Configure global response headers for JSON content"""
  70. @app.after_request
  71. def after_request(response):
  72. from flask import request
  73. # 检查是否是API路径
  74. if request.path.startswith("/api/"):
  75. # 排除文件下载和特殊响应类型
  76. excluded_types = [
  77. "application/octet-stream",
  78. "application/pdf",
  79. "image/",
  80. "text/csv",
  81. "application/vnd.ms-excel",
  82. "application/vnd.openxmlformats-officedocument",
  83. ]
  84. if response.content_type and any(
  85. ct in response.content_type for ct in excluded_types
  86. ):
  87. # 保持原有的文件类型不变
  88. pass
  89. elif response.content_type and "application/json" in response.content_type:
  90. # 确保JSON响应设置正确的Content-Type和charset
  91. ct = "application/json; charset=utf-8"
  92. response.headers["Content-Type"] = ct
  93. elif (
  94. not response.content_type
  95. or response.content_type == "text/html; charset=utf-8"
  96. or response.content_type == "text/plain"
  97. ):
  98. # 对于API路由,默认设置为JSON
  99. ct = "application/json; charset=utf-8"
  100. response.headers["Content-Type"] = ct
  101. # 确保CORS头部不被覆盖
  102. if "Access-Control-Allow-Origin" not in response.headers:
  103. # 动态设置Origin,支持任意前端地址
  104. origin = request.headers.get("Origin")
  105. if origin:
  106. # 允许任意Origin(最灵活的配置)
  107. response.headers["Access-Control-Allow-Origin"] = origin
  108. else:
  109. # 如果没有Origin头部,设置为通配符
  110. response.headers["Access-Control-Allow-Origin"] = "*"
  111. # 专门处理预检请求(OPTIONS方法)
  112. if request.method == "OPTIONS":
  113. origin = request.headers.get("Origin", "*")
  114. response.headers["Access-Control-Allow-Origin"] = origin
  115. methods = "GET, POST, PUT, DELETE, OPTIONS"
  116. response.headers["Access-Control-Allow-Methods"] = methods
  117. headers = (
  118. "Content-Type, Authorization, X-Requested-With, "
  119. "Accept, Origin, Cache-Control, X-File-Name"
  120. )
  121. response.headers["Access-Control-Allow-Headers"] = headers
  122. response.headers["Access-Control-Max-Age"] = "86400"
  123. return response
  124. # 根据配置设置凭据支持
  125. from app.config.cors import ALLOW_ALL_ORIGINS
  126. if "Access-Control-Allow-Credentials" not in response.headers:
  127. if ALLOW_ALL_ORIGINS:
  128. # 通配符时不支持凭据
  129. response.headers["Access-Control-Allow-Credentials"] = "false"
  130. else:
  131. response.headers["Access-Control-Allow-Credentials"] = "true"
  132. if "Access-Control-Allow-Methods" not in response.headers:
  133. methods = "GET, POST, PUT, DELETE, OPTIONS"
  134. response.headers["Access-Control-Allow-Methods"] = methods
  135. if "Access-Control-Allow-Headers" not in response.headers:
  136. headers = (
  137. "Content-Type, Authorization, X-Requested-With, Accept, Origin"
  138. )
  139. response.headers["Access-Control-Allow-Headers"] = headers
  140. # 添加安全头部
  141. if "X-Content-Type-Options" not in response.headers:
  142. response.headers["X-Content-Type-Options"] = "nosniff"
  143. if "X-Frame-Options" not in response.headers:
  144. response.headers["X-Frame-Options"] = "DENY"
  145. if "X-XSS-Protection" not in response.headers:
  146. response.headers["X-XSS-Protection"] = "1; mode=block"
  147. if "Referrer-Policy" not in response.headers:
  148. response.headers["Referrer-Policy"] = "no-referrer"
  149. if "Permissions-Policy" not in response.headers:
  150. response.headers["Permissions-Policy"] = (
  151. "camera=(), microphone=(), geolocation=()"
  152. )
  153. if (
  154. request.path.startswith("/api/system/auth")
  155. or request.path.startswith(
  156. "/api/system/governance-audit"
  157. )
  158. ):
  159. response.headers["Cache-Control"] = "no-store"
  160. if request.path.startswith("/api/") and request.path != "/api/system/health":
  161. app.logger.info(
  162. "%s %s -> %s",
  163. request.method,
  164. request.path,
  165. response.status_code,
  166. )
  167. return response
  168. def configure_logging(app):
  169. """Configure logging for the application"""
  170. if not app.config.get("LOG_ENABLED", True):
  171. return None
  172. log_file = os.path.abspath(
  173. app.config.get("LOG_FILE", f"flask_{app.config['FLASK_ENV']}.log")
  174. )
  175. log_dir = os.path.dirname(log_file)
  176. if log_dir:
  177. os.makedirs(log_dir, exist_ok=True)
  178. log_level_name = app.config.get("LOG_LEVEL", "INFO")
  179. log_level = getattr(logging, log_level_name)
  180. log_format = app.config.get(
  181. "LOG_FORMAT",
  182. "%(asctime)s - %(levelname)s - %(filename)s - "
  183. "%(funcName)s - %(lineno)s - %(message)s",
  184. )
  185. log_encoding = app.config.get("LOG_ENCODING", "UTF-8")
  186. log_to_console = app.config.get("LOG_TO_CONSOLE", True)
  187. logging_format = logging.Formatter(log_format)
  188. root_logger = logging.getLogger()
  189. root_logger.setLevel(log_level)
  190. root_logger.handlers.clear()
  191. file_handler = logging.FileHandler(log_file, encoding=log_encoding)
  192. file_handler.setLevel(log_level)
  193. file_handler.setFormatter(logging_format)
  194. root_logger.addHandler(file_handler)
  195. if log_to_console:
  196. console = logging.StreamHandler()
  197. console.setLevel(log_level)
  198. console.setFormatter(logging_format)
  199. root_logger.addHandler(console)
  200. # Flask 默认 logger 关闭 propagate,清空 handler 后需要显式开启
  201. app.logger.handlers.clear()
  202. app.logger.propagate = True
  203. app.logger.setLevel(log_level)
  204. for logger_name in ("app", "flask.app"):
  205. named_logger = logging.getLogger(logger_name)
  206. named_logger.handlers.clear()
  207. named_logger.propagate = True
  208. named_logger.setLevel(log_level)
  209. app.logger.info(f"日志配置完成: 级别={log_level_name}, 文件={log_file}")
  210. return logging.getLogger("app")
  211. def configure_error_handlers(app):
  212. """Configure global error handlers for the application"""
  213. @app.errorhandler(Exception)
  214. def handle_exception(e):
  215. """全局异常处理器,捕获所有未处理的异常"""
  216. from app.core.data_source.redaction import sanitize_exception
  217. correlation_id = str(uuid.uuid4())
  218. app.logger.error(
  219. "未处理的异常 correlation_id=%s type=%s detail=%s",
  220. correlation_id,
  221. type(e).__name__,
  222. sanitize_exception(e, limit=300),
  223. )
  224. error_response = {
  225. "success": False,
  226. "message": "服务器内部错误",
  227. "data": None,
  228. "correlation_id": correlation_id,
  229. }
  230. return jsonify(error_response), 500
  231. @app.errorhandler(404)
  232. def handle_not_found(e):
  233. """处理404错误"""
  234. app.logger.warning(f"404错误: {str(e)}")
  235. return jsonify(
  236. {"success": False, "message": "请求的资源不存在", "data": None}
  237. ), 404
  238. @app.errorhandler(500)
  239. def handle_internal_error(e):
  240. """处理500错误"""
  241. correlation_id = str(uuid.uuid4())
  242. app.logger.error(
  243. "500错误 correlation_id=%s type=%s",
  244. correlation_id,
  245. type(e).__name__,
  246. )
  247. return jsonify(
  248. {
  249. "success": False,
  250. "message": "服务器内部错误",
  251. "data": None,
  252. "correlation_id": correlation_id,
  253. }
  254. ), 500