app.py 6.5 KB

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