Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

__init__.py 3.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  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 api.db import StatusEnum
  25. from api.db.db_models import close_connection
  26. from api.db.services import UserService
  27. from api.utils import CustomJSONEncoder, commands
  28. from flask_session import Session
  29. from flask_login import LoginManager
  30. from api.settings import SECRET_KEY, stat_logger
  31. from api.settings import API_VERSION, access_logger
  32. from api.utils.api_utils import server_error_response
  33. from itsdangerous.url_safe import URLSafeTimedSerializer as Serializer
  34. __all__ = ['app']
  35. logger = logging.getLogger('flask.app')
  36. for h in access_logger.handlers:
  37. logger.addHandler(h)
  38. Request.json = property(lambda self: self.get_json(force=True, silent=True))
  39. app = Flask(__name__)
  40. CORS(app, supports_credentials=True,max_age=2592000)
  41. app.url_map.strict_slashes = False
  42. app.json_encoder = CustomJSONEncoder
  43. app.errorhandler(Exception)(server_error_response)
  44. ## convince for dev and debug
  45. #app.config["LOGIN_DISABLED"] = True
  46. app.config["SESSION_PERMANENT"] = False
  47. app.config["SESSION_TYPE"] = "filesystem"
  48. app.config['MAX_CONTENT_LENGTH'] = int(os.environ.get("MAX_CONTENT_LENGTH", 128 * 1024 * 1024))
  49. Session(app)
  50. login_manager = LoginManager()
  51. login_manager.init_app(app)
  52. commands.register_commands(app)
  53. def search_pages_path(pages_dir):
  54. app_path_list = [path for path in pages_dir.glob('*_app.py') if not path.name.startswith('.')]
  55. api_path_list = [path for path in pages_dir.glob('*_api.py') if not path.name.startswith('.')]
  56. app_path_list.extend(api_path_list)
  57. return app_path_list
  58. def register_page(page_path):
  59. path = f'{page_path}'
  60. page_name = page_path.stem.rstrip('_api') if "_api" in path else page_path.stem.rstrip('_app')
  61. module_name = '.'.join(page_path.parts[page_path.parts.index('api'):-1] + (page_name,))
  62. spec = spec_from_file_location(module_name, page_path)
  63. page = module_from_spec(spec)
  64. page.app = app
  65. page.manager = Blueprint(page_name, module_name)
  66. sys.modules[module_name] = page
  67. spec.loader.exec_module(page)
  68. page_name = getattr(page, 'page_name', page_name)
  69. url_prefix = f'/api/{API_VERSION}/{page_name}' if "_api" in path else f'/{API_VERSION}/{page_name}'
  70. app.register_blueprint(page.manager, url_prefix=url_prefix)
  71. return url_prefix
  72. pages_dir = [
  73. Path(__file__).parent,
  74. Path(__file__).parent.parent / 'api' / 'apps', # FIXME: ragflow/api/api/apps, can be remove?
  75. ]
  76. client_urls_prefix = [
  77. register_page(path)
  78. for dir in pages_dir
  79. for path in search_pages_path(dir)
  80. ]
  81. @login_manager.request_loader
  82. def load_user(web_request):
  83. jwt = Serializer(secret_key=SECRET_KEY)
  84. authorization = web_request.headers.get("Authorization")
  85. if authorization:
  86. try:
  87. access_token = str(jwt.loads(authorization))
  88. user = UserService.query(access_token=access_token, status=StatusEnum.VALID.value)
  89. if user:
  90. return user[0]
  91. else:
  92. return None
  93. except Exception as e:
  94. stat_logger.exception(e)
  95. return None
  96. else:
  97. return None
  98. @app.teardown_request
  99. def _db_close(exc):
  100. close_connection()