You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 3.5KB

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