app.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  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. CORS(service_api_bp,
  99. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  100. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH']
  101. )
  102. app.register_blueprint(service_api_bp)
  103. CORS(web_bp,
  104. resources={
  105. r"/*": {"origins": app.config['WEB_API_CORS_ALLOW_ORIGINS']}},
  106. supports_credentials=True,
  107. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  108. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  109. expose_headers=['X-Version', 'X-Env']
  110. )
  111. app.register_blueprint(web_bp)
  112. CORS(console_app_bp,
  113. resources={
  114. r"/*": {"origins": app.config['CONSOLE_CORS_ALLOW_ORIGINS']}},
  115. supports_credentials=True,
  116. allow_headers=['Content-Type', 'Authorization'],
  117. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  118. expose_headers=['X-Version', 'X-Env']
  119. )
  120. app.register_blueprint(console_app_bp)
  121. # create app
  122. app = create_app()
  123. celery = app.extensions["celery"]
  124. if app.config['TESTING']:
  125. print("App is running in TESTING mode")
  126. @app.after_request
  127. def after_request(response):
  128. """Add Version headers to the response."""
  129. response.set_cookie('remember_token', '', expires=0)
  130. response.headers.add('X-Version', app.config['CURRENT_VERSION'])
  131. response.headers.add('X-Env', app.config['DEPLOY_ENV'])
  132. return response
  133. @app.route('/health')
  134. def health():
  135. return Response(json.dumps({
  136. 'status': 'ok',
  137. 'version': app.config['CURRENT_VERSION']
  138. }), status=200, content_type="application/json")
  139. @app.route('/threads')
  140. def threads():
  141. num_threads = threading.active_count()
  142. threads = threading.enumerate()
  143. thread_list = []
  144. for thread in threads:
  145. thread_name = thread.name
  146. thread_id = thread.ident
  147. is_alive = thread.is_alive()
  148. thread_list.append({
  149. 'name': thread_name,
  150. 'id': thread_id,
  151. 'is_alive': is_alive
  152. })
  153. return {
  154. 'thread_num': num_threads,
  155. 'threads': thread_list
  156. }
  157. @app.route('/db-pool-stat')
  158. def pool_stat():
  159. engine = db.engine
  160. return {
  161. 'pool_size': engine.pool.size(),
  162. 'checked_in_connections': engine.pool.checkedin(),
  163. 'checked_out_connections': engine.pool.checkedout(),
  164. 'overflow_connections': engine.pool.overflow(),
  165. 'connection_timeout': engine.pool.timeout(),
  166. 'recycle_time': db.engine.pool._recycle
  167. }
  168. if __name__ == '__main__':
  169. app.run(host='0.0.0.0', port=5001)