app.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. # -*- coding:utf-8 -*-
  2. import os
  3. from werkzeug.exceptions import Unauthorized
  4. if not os.environ.get("DEBUG") or os.environ.get("DEBUG").lower() != 'true':
  5. from gevent import monkey
  6. monkey.patch_all()
  7. if os.environ.get("VECTOR_STORE") == 'milvus':
  8. import grpc.experimental.gevent
  9. grpc.experimental.gevent.init_gevent()
  10. import time
  11. import logging
  12. import json
  13. import threading
  14. from flask import Flask, request, Response
  15. from flask_cors import CORS
  16. from core.model_providers.providers import hosted
  17. from extensions import ext_celery, ext_sentry, ext_redis, ext_login, ext_migrate, \
  18. ext_database, ext_storage, ext_mail, ext_code_based_extension
  19. from extensions.ext_database import db
  20. from extensions.ext_login import login_manager
  21. # DO NOT REMOVE BELOW
  22. from models import model, account, dataset, web, task, source, tool
  23. from events import event_handlers
  24. # DO NOT REMOVE ABOVE
  25. from config import Config, CloudEditionConfig
  26. from commands import register_commands
  27. from services.account_service import AccountService
  28. from libs.passport import PassportService
  29. import warnings
  30. warnings.simplefilter("ignore", ResourceWarning)
  31. # fix windows platform
  32. if os.name == "nt":
  33. os.system('tzutil /s "UTC"')
  34. else:
  35. os.environ['TZ'] = 'UTC'
  36. time.tzset()
  37. class DifyApp(Flask):
  38. pass
  39. # -------------
  40. # Configuration
  41. # -------------
  42. config_type = os.getenv('EDITION', default='SELF_HOSTED') # ce edition first
  43. # ----------------------------
  44. # Application Factory Function
  45. # ----------------------------
  46. def create_app(test_config=None) -> Flask:
  47. app = DifyApp(__name__)
  48. if test_config:
  49. app.config.from_object(test_config)
  50. else:
  51. if config_type == "CLOUD":
  52. app.config.from_object(CloudEditionConfig())
  53. else:
  54. app.config.from_object(Config())
  55. app.secret_key = app.config['SECRET_KEY']
  56. logging.basicConfig(level=app.config.get('LOG_LEVEL', 'INFO'))
  57. initialize_extensions(app)
  58. register_blueprints(app)
  59. register_commands(app)
  60. hosted.init_app(app)
  61. return app
  62. def initialize_extensions(app):
  63. # Since the application instance is now created, pass it to each Flask
  64. # extension instance to bind it to the Flask application instance (app)
  65. ext_code_based_extension.init()
  66. ext_database.init_app(app)
  67. ext_migrate.init(app, db)
  68. ext_redis.init_app(app)
  69. ext_storage.init_app(app)
  70. ext_celery.init_app(app)
  71. ext_login.init_app(app)
  72. ext_mail.init_app(app)
  73. ext_sentry.init_app(app)
  74. # Flask-Login configuration
  75. @login_manager.request_loader
  76. def load_user_from_request(request_from_flask_login):
  77. """Load user based on the request."""
  78. if request.blueprint == 'console':
  79. # Check if the user_id contains a dot, indicating the old format
  80. auth_header = request.headers.get('Authorization', '')
  81. if ' ' not in auth_header:
  82. raise Unauthorized('Invalid Authorization header format. Expected \'Bearer <api-key>\' format.')
  83. auth_scheme, auth_token = auth_header.split(None, 1)
  84. auth_scheme = auth_scheme.lower()
  85. if auth_scheme != 'bearer':
  86. raise Unauthorized('Invalid Authorization header format. Expected \'Bearer <api-key>\' format.')
  87. decoded = PassportService().verify(auth_token)
  88. user_id = decoded.get('user_id')
  89. return AccountService.load_user(user_id)
  90. else:
  91. return None
  92. @login_manager.unauthorized_handler
  93. def unauthorized_handler():
  94. """Handle unauthorized requests."""
  95. return Response(json.dumps({
  96. 'code': 'unauthorized',
  97. 'message': "Unauthorized."
  98. }), status=401, content_type="application/json")
  99. # register blueprint routers
  100. def register_blueprints(app):
  101. from controllers.service_api import bp as service_api_bp
  102. from controllers.web import bp as web_bp
  103. from controllers.console import bp as console_app_bp
  104. from controllers.files import bp as files_bp
  105. CORS(service_api_bp,
  106. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  107. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH']
  108. )
  109. app.register_blueprint(service_api_bp)
  110. CORS(web_bp,
  111. resources={
  112. r"/*": {"origins": app.config['WEB_API_CORS_ALLOW_ORIGINS']}},
  113. supports_credentials=True,
  114. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  115. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  116. expose_headers=['X-Version', 'X-Env']
  117. )
  118. app.register_blueprint(web_bp)
  119. CORS(console_app_bp,
  120. resources={
  121. r"/*": {"origins": app.config['CONSOLE_CORS_ALLOW_ORIGINS']}},
  122. supports_credentials=True,
  123. allow_headers=['Content-Type', 'Authorization'],
  124. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  125. expose_headers=['X-Version', 'X-Env']
  126. )
  127. app.register_blueprint(console_app_bp)
  128. CORS(files_bp,
  129. allow_headers=['Content-Type'],
  130. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH']
  131. )
  132. app.register_blueprint(files_bp)
  133. # create app
  134. app = create_app()
  135. celery = app.extensions["celery"]
  136. if app.config['TESTING']:
  137. print("App is running in TESTING mode")
  138. @app.after_request
  139. def after_request(response):
  140. """Add Version headers to the response."""
  141. response.set_cookie('remember_token', '', expires=0)
  142. response.headers.add('X-Version', app.config['CURRENT_VERSION'])
  143. response.headers.add('X-Env', app.config['DEPLOY_ENV'])
  144. return response
  145. @app.route('/health')
  146. def health():
  147. return Response(json.dumps({
  148. 'status': 'ok',
  149. 'version': app.config['CURRENT_VERSION']
  150. }), status=200, content_type="application/json")
  151. @app.route('/threads')
  152. def threads():
  153. num_threads = threading.active_count()
  154. threads = threading.enumerate()
  155. thread_list = []
  156. for thread in threads:
  157. thread_name = thread.name
  158. thread_id = thread.ident
  159. is_alive = thread.is_alive()
  160. thread_list.append({
  161. 'name': thread_name,
  162. 'id': thread_id,
  163. 'is_alive': is_alive
  164. })
  165. return {
  166. 'thread_num': num_threads,
  167. 'threads': thread_list
  168. }
  169. @app.route('/db-pool-stat')
  170. def pool_stat():
  171. engine = db.engine
  172. return {
  173. 'pool_size': engine.pool.size(),
  174. 'checked_in_connections': engine.pool.checkedin(),
  175. 'checked_out_connections': engine.pool.checkedout(),
  176. 'overflow_connections': engine.pool.overflow(),
  177. 'connection_timeout': engine.pool.timeout(),
  178. 'recycle_time': db.engine.pool._recycle
  179. }
  180. if __name__ == '__main__':
  181. app.run(host='0.0.0.0', port=5001)