__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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, If-Match, "
  120. "X-Agent-Credential"
  121. )
  122. response.headers["Access-Control-Allow-Headers"] = headers
  123. response.headers["Access-Control-Max-Age"] = "86400"
  124. return response
  125. # 根据配置设置凭据支持
  126. from app.config.cors import ALLOW_ALL_ORIGINS
  127. if "Access-Control-Allow-Credentials" not in response.headers:
  128. if ALLOW_ALL_ORIGINS:
  129. # 通配符时不支持凭据
  130. response.headers["Access-Control-Allow-Credentials"] = "false"
  131. else:
  132. response.headers["Access-Control-Allow-Credentials"] = "true"
  133. if "Access-Control-Allow-Methods" not in response.headers:
  134. methods = "GET, POST, PUT, DELETE, OPTIONS"
  135. response.headers["Access-Control-Allow-Methods"] = methods
  136. if "Access-Control-Allow-Headers" not in response.headers:
  137. headers = (
  138. "Content-Type, Authorization, X-Requested-With, Accept, Origin, "
  139. "If-Match, X-Agent-Credential"
  140. )
  141. response.headers["Access-Control-Allow-Headers"] = headers
  142. # 添加安全头部
  143. if "X-Content-Type-Options" not in response.headers:
  144. response.headers["X-Content-Type-Options"] = "nosniff"
  145. if "X-Frame-Options" not in response.headers:
  146. response.headers["X-Frame-Options"] = "DENY"
  147. if "X-XSS-Protection" not in response.headers:
  148. response.headers["X-XSS-Protection"] = "1; mode=block"
  149. if "Referrer-Policy" not in response.headers:
  150. response.headers["Referrer-Policy"] = "no-referrer"
  151. if "Permissions-Policy" not in response.headers:
  152. response.headers["Permissions-Policy"] = (
  153. "camera=(), microphone=(), geolocation=()"
  154. )
  155. if (
  156. request.path.startswith("/api/system/auth")
  157. or request.path.startswith(
  158. "/api/system/governance-audit"
  159. )
  160. ):
  161. response.headers["Cache-Control"] = "no-store"
  162. if request.path.startswith("/api/") and request.path != "/api/system/health":
  163. app.logger.info(
  164. "%s %s -> %s",
  165. request.method,
  166. request.path,
  167. response.status_code,
  168. )
  169. return response
  170. def configure_logging(app):
  171. """Configure logging for the application"""
  172. if not app.config.get("LOG_ENABLED", True):
  173. return None
  174. log_file = os.path.abspath(
  175. app.config.get("LOG_FILE", f"flask_{app.config['FLASK_ENV']}.log")
  176. )
  177. log_dir = os.path.dirname(log_file)
  178. if log_dir:
  179. os.makedirs(log_dir, exist_ok=True)
  180. log_level_name = app.config.get("LOG_LEVEL", "INFO")
  181. log_level = getattr(logging, log_level_name)
  182. log_format = app.config.get(
  183. "LOG_FORMAT",
  184. "%(asctime)s - %(levelname)s - %(filename)s - "
  185. "%(funcName)s - %(lineno)s - %(message)s",
  186. )
  187. log_encoding = app.config.get("LOG_ENCODING", "UTF-8")
  188. log_to_console = app.config.get("LOG_TO_CONSOLE", True)
  189. logging_format = logging.Formatter(log_format)
  190. root_logger = logging.getLogger()
  191. root_logger.setLevel(log_level)
  192. root_logger.handlers.clear()
  193. file_handler = logging.FileHandler(log_file, encoding=log_encoding)
  194. file_handler.setLevel(log_level)
  195. file_handler.setFormatter(logging_format)
  196. root_logger.addHandler(file_handler)
  197. if log_to_console:
  198. console = logging.StreamHandler()
  199. console.setLevel(log_level)
  200. console.setFormatter(logging_format)
  201. root_logger.addHandler(console)
  202. # Flask 默认 logger 关闭 propagate,清空 handler 后需要显式开启
  203. app.logger.handlers.clear()
  204. app.logger.propagate = True
  205. app.logger.setLevel(log_level)
  206. for logger_name in ("app", "flask.app"):
  207. named_logger = logging.getLogger(logger_name)
  208. named_logger.handlers.clear()
  209. named_logger.propagate = True
  210. named_logger.setLevel(log_level)
  211. app.logger.info(f"日志配置完成: 级别={log_level_name}, 文件={log_file}")
  212. return logging.getLogger("app")
  213. def configure_error_handlers(app):
  214. """Configure global error handlers for the application"""
  215. @app.errorhandler(Exception)
  216. def handle_exception(e):
  217. """全局异常处理器,捕获所有未处理的异常"""
  218. from app.core.data_source.redaction import sanitize_exception
  219. correlation_id = str(uuid.uuid4())
  220. app.logger.error(
  221. "未处理的异常 correlation_id=%s type=%s detail=%s",
  222. correlation_id,
  223. type(e).__name__,
  224. sanitize_exception(e, limit=300),
  225. )
  226. error_response = {
  227. "success": False,
  228. "message": "服务器内部错误",
  229. "data": None,
  230. "correlation_id": correlation_id,
  231. }
  232. return jsonify(error_response), 500
  233. @app.errorhandler(404)
  234. def handle_not_found(e):
  235. """处理404错误"""
  236. app.logger.warning(f"404错误: {str(e)}")
  237. return jsonify(
  238. {"success": False, "message": "请求的资源不存在", "data": None}
  239. ), 404
  240. @app.errorhandler(500)
  241. def handle_internal_error(e):
  242. """处理500错误"""
  243. correlation_id = str(uuid.uuid4())
  244. app.logger.error(
  245. "500错误 correlation_id=%s type=%s",
  246. correlation_id,
  247. type(e).__name__,
  248. )
  249. return jsonify(
  250. {
  251. "success": False,
  252. "message": "服务器内部错误",
  253. "data": None,
  254. "correlation_id": correlation_id,
  255. }
  256. ), 500