Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

__init__.py 4.6KB

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