Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. import os
  18. import sys
  19. from importlib.util import module_from_spec, spec_from_file_location
  20. from pathlib import Path
  21. from flask import Blueprint, Flask
  22. from werkzeug.wrappers.request import Request
  23. from flask_cors import CORS
  24. from flasgger import Swagger
  25. from api.db import StatusEnum
  26. from api.db.db_models import close_connection
  27. from api.db.services import UserService
  28. from api.utils import CustomJSONEncoder, commands
  29. from flask_session import Session
  30. from flask_login import LoginManager
  31. from api.settings import SECRET_KEY, stat_logger
  32. from api.settings import API_VERSION, access_logger
  33. from api.utils.api_utils import server_error_response
  34. from itsdangerous.url_safe import URLSafeTimedSerializer as Serializer
  35. __all__ = ["app"]
  36. logger = logging.getLogger("flask.app")
  37. for h in access_logger.handlers:
  38. logger.addHandler(h)
  39. Request.json = property(lambda self: self.get_json(force=True, silent=True))
  40. app = Flask(__name__)
  41. # Add this at the beginning of your file to configure Swagger UI
  42. swagger_config = {
  43. "headers": [],
  44. "specs": [
  45. {
  46. "endpoint": "apispec",
  47. "route": "/apispec.json",
  48. "rule_filter": lambda rule: True, # Include all endpoints
  49. "model_filter": lambda tag: True, # Include all models
  50. }
  51. ],
  52. "static_url_path": "/flasgger_static",
  53. "swagger_ui": True,
  54. "specs_route": "/apidocs/",
  55. }
  56. swagger = Swagger(
  57. app,
  58. config=swagger_config,
  59. template={
  60. "swagger": "2.0",
  61. "info": {
  62. "title": "RAGFlow API",
  63. "description": "",
  64. "version": "1.0.0",
  65. },
  66. "securityDefinitions": {
  67. "ApiKeyAuth": {"type": "apiKey", "name": "Authorization", "in": "header"}
  68. },
  69. },
  70. )
  71. CORS(app, supports_credentials=True, max_age=2592000)
  72. app.url_map.strict_slashes = False
  73. app.json_encoder = CustomJSONEncoder
  74. app.errorhandler(Exception)(server_error_response)
  75. ## convince for dev and debug
  76. # app.config["LOGIN_DISABLED"] = True
  77. app.config["SESSION_PERMANENT"] = False
  78. app.config["SESSION_TYPE"] = "filesystem"
  79. app.config["MAX_CONTENT_LENGTH"] = int(
  80. os.environ.get("MAX_CONTENT_LENGTH", 128 * 1024 * 1024)
  81. )
  82. Session(app)
  83. login_manager = LoginManager()
  84. login_manager.init_app(app)
  85. commands.register_commands(app)
  86. def search_pages_path(pages_dir):
  87. app_path_list = [
  88. path for path in pages_dir.glob("*_app.py") if not path.name.startswith(".")
  89. ]
  90. api_path_list = [
  91. path for path in pages_dir.glob("*sdk/*.py") if not path.name.startswith(".")
  92. ]
  93. app_path_list.extend(api_path_list)
  94. return app_path_list
  95. def register_page(page_path):
  96. path = f"{page_path}"
  97. page_name = page_path.stem.rstrip("_app")
  98. module_name = ".".join(
  99. page_path.parts[page_path.parts.index("api") : -1] + (page_name,)
  100. )
  101. spec = spec_from_file_location(module_name, page_path)
  102. page = module_from_spec(spec)
  103. page.app = app
  104. page.manager = Blueprint(page_name, module_name)
  105. sys.modules[module_name] = page
  106. spec.loader.exec_module(page)
  107. page_name = getattr(page, "page_name", page_name)
  108. url_prefix = (
  109. f"/api/{API_VERSION}" if "/sdk/" in path else f"/{API_VERSION}/{page_name}"
  110. )
  111. app.register_blueprint(page.manager, url_prefix=url_prefix)
  112. return url_prefix
  113. pages_dir = [
  114. Path(__file__).parent,
  115. Path(__file__).parent.parent / "api" / "apps",
  116. Path(__file__).parent.parent / "api" / "apps" / "sdk",
  117. ]
  118. client_urls_prefix = [
  119. register_page(path) for dir in pages_dir for path in search_pages_path(dir)
  120. ]
  121. @login_manager.request_loader
  122. def load_user(web_request):
  123. jwt = Serializer(secret_key=SECRET_KEY)
  124. authorization = web_request.headers.get("Authorization")
  125. if authorization:
  126. try:
  127. access_token = str(jwt.loads(authorization))
  128. user = UserService.query(
  129. access_token=access_token, status=StatusEnum.VALID.value
  130. )
  131. if user:
  132. return user[0]
  133. else:
  134. return None
  135. except Exception as e:
  136. stat_logger.exception(e)
  137. return None
  138. else:
  139. return None
  140. @app.teardown_request
  141. def _db_close(exc):
  142. close_connection()