您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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 os
  17. import sys
  18. import logging
  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 itsdangerous.url_safe import URLSafeTimedSerializer as Serializer
  26. from api.db import StatusEnum
  27. from api.db.db_models import close_connection
  28. from api.db.services import UserService
  29. from api.utils import CustomJSONEncoder, commands
  30. from flask_session import Session
  31. from flask_login import LoginManager
  32. from api import settings
  33. from api.utils.api_utils import server_error_response
  34. from api.constants import API_VERSION
  35. __all__ = ["app"]
  36. Request.json = property(lambda self: self.get_json(force=True, silent=True))
  37. app = Flask(__name__)
  38. # Add this at the beginning of your file to configure Swagger UI
  39. swagger_config = {
  40. "headers": [],
  41. "specs": [
  42. {
  43. "endpoint": "apispec",
  44. "route": "/apispec.json",
  45. "rule_filter": lambda rule: True, # Include all endpoints
  46. "model_filter": lambda tag: True, # Include all models
  47. }
  48. ],
  49. "static_url_path": "/flasgger_static",
  50. "swagger_ui": True,
  51. "specs_route": "/apidocs/",
  52. }
  53. swagger = Swagger(
  54. app,
  55. config=swagger_config,
  56. template={
  57. "swagger": "2.0",
  58. "info": {
  59. "title": "RAGFlow API",
  60. "description": "",
  61. "version": "1.0.0",
  62. },
  63. "securityDefinitions": {
  64. "ApiKeyAuth": {"type": "apiKey", "name": "Authorization", "in": "header"}
  65. },
  66. },
  67. )
  68. CORS(app, supports_credentials=True, max_age=2592000)
  69. app.url_map.strict_slashes = False
  70. app.json_encoder = CustomJSONEncoder
  71. app.errorhandler(Exception)(server_error_response)
  72. ## convince for dev and debug
  73. # app.config["LOGIN_DISABLED"] = True
  74. app.config["SESSION_PERMANENT"] = False
  75. app.config["SESSION_TYPE"] = "filesystem"
  76. app.config["MAX_CONTENT_LENGTH"] = int(
  77. os.environ.get("MAX_CONTENT_LENGTH", 128 * 1024 * 1024)
  78. )
  79. Session(app)
  80. login_manager = LoginManager()
  81. login_manager.init_app(app)
  82. commands.register_commands(app)
  83. def search_pages_path(pages_dir):
  84. app_path_list = [
  85. path for path in pages_dir.glob("*_app.py") if not path.name.startswith(".")
  86. ]
  87. api_path_list = [
  88. path for path in pages_dir.glob("*sdk/*.py") if not path.name.startswith(".")
  89. ]
  90. app_path_list.extend(api_path_list)
  91. return app_path_list
  92. def register_page(page_path):
  93. path = f"{page_path}"
  94. page_name = page_path.stem.rstrip("_app")
  95. module_name = ".".join(
  96. page_path.parts[page_path.parts.index("api"): -1] + (page_name,)
  97. )
  98. spec = spec_from_file_location(module_name, page_path)
  99. page = module_from_spec(spec)
  100. page.app = app
  101. page.manager = Blueprint(page_name, module_name)
  102. sys.modules[module_name] = page
  103. spec.loader.exec_module(page)
  104. page_name = getattr(page, "page_name", page_name)
  105. url_prefix = (
  106. f"/api/{API_VERSION}" if "/sdk/" in path else f"/{API_VERSION}/{page_name}"
  107. )
  108. app.register_blueprint(page.manager, url_prefix=url_prefix)
  109. return url_prefix
  110. pages_dir = [
  111. Path(__file__).parent,
  112. Path(__file__).parent.parent / "api" / "apps",
  113. Path(__file__).parent.parent / "api" / "apps" / "sdk",
  114. ]
  115. client_urls_prefix = [
  116. register_page(path) for dir in pages_dir for path in search_pages_path(dir)
  117. ]
  118. @login_manager.request_loader
  119. def load_user(web_request):
  120. jwt = Serializer(secret_key=settings.SECRET_KEY)
  121. authorization = web_request.headers.get("Authorization")
  122. if authorization:
  123. try:
  124. access_token = str(jwt.loads(authorization))
  125. user = UserService.query(
  126. access_token=access_token, status=StatusEnum.VALID.value
  127. )
  128. if user:
  129. return user[0]
  130. else:
  131. return None
  132. except Exception:
  133. logging.exception("load_user got exception")
  134. return None
  135. else:
  136. return None
  137. @app.teardown_request
  138. def _db_close(exc):
  139. close_connection()