app.py 6.1 KB

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