app.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. # -*- coding:utf-8 -*-
  2. import os
  3. if not os.environ.get("DEBUG") or os.environ.get("DEBUG").lower() != 'true':
  4. from gevent import monkey
  5. monkey.patch_all()
  6. import logging
  7. import json
  8. import threading
  9. from flask import Flask, request, Response, session
  10. import flask_login
  11. from flask_cors import CORS
  12. from extensions import ext_session, ext_celery, ext_sentry, ext_redis, ext_login, ext_vector_store, ext_migrate, \
  13. ext_database, ext_storage
  14. from extensions.ext_database import db
  15. from extensions.ext_login import login_manager
  16. # DO NOT REMOVE BELOW
  17. from models import model, account, dataset, web, task
  18. from events import event_handlers
  19. # DO NOT REMOVE ABOVE
  20. import core
  21. from config import Config, CloudEditionConfig
  22. from commands import register_commands
  23. from models.account import TenantAccountJoin
  24. from models.model import Account, EndUser, App
  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. core.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_vector_store.init_app(app)
  59. ext_storage.init_app(app)
  60. ext_celery.init_app(app)
  61. ext_session.init_app(app)
  62. ext_login.init_app(app)
  63. ext_sentry.init_app(app)
  64. # Flask-Login configuration
  65. @login_manager.user_loader
  66. def load_user(user_id):
  67. """Load user based on the user_id."""
  68. if request.blueprint == 'console':
  69. # Check if the user_id contains a dot, indicating the old format
  70. if '.' in user_id:
  71. tenant_id, account_id = user_id.split('.')
  72. else:
  73. account_id = user_id
  74. account = db.session.query(Account).filter(Account.id == account_id).first()
  75. if account:
  76. workspace_id = session.get('workspace_id')
  77. if workspace_id:
  78. tenant_account_join = db.session.query(TenantAccountJoin).filter(
  79. TenantAccountJoin.account_id == account.id,
  80. TenantAccountJoin.tenant_id == workspace_id
  81. ).first()
  82. if not tenant_account_join:
  83. tenant_account_join = db.session.query(TenantAccountJoin).filter(
  84. TenantAccountJoin.account_id == account.id).first()
  85. if tenant_account_join:
  86. account.current_tenant_id = tenant_account_join.tenant_id
  87. session['workspace_id'] = account.current_tenant_id
  88. else:
  89. account.current_tenant_id = workspace_id
  90. else:
  91. tenant_account_join = db.session.query(TenantAccountJoin).filter(
  92. TenantAccountJoin.account_id == account.id).first()
  93. if tenant_account_join:
  94. account.current_tenant_id = tenant_account_join.tenant_id
  95. session['workspace_id'] = account.current_tenant_id
  96. # Log in the user with the updated user_id
  97. flask_login.login_user(account, remember=True)
  98. return account
  99. else:
  100. return None
  101. @login_manager.unauthorized_handler
  102. def unauthorized_handler():
  103. """Handle unauthorized requests."""
  104. return Response(json.dumps({
  105. 'code': 'unauthorized',
  106. 'message': "Unauthorized."
  107. }), status=401, content_type="application/json")
  108. # register blueprint routers
  109. def register_blueprints(app):
  110. from controllers.service_api import bp as service_api_bp
  111. from controllers.web import bp as web_bp
  112. from controllers.console import bp as console_app_bp
  113. app.register_blueprint(service_api_bp)
  114. CORS(web_bp,
  115. resources={
  116. r"/*": {"origins": app.config['WEB_API_CORS_ALLOW_ORIGINS']}},
  117. supports_credentials=True,
  118. allow_headers=['Content-Type', 'Authorization'],
  119. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  120. expose_headers=['X-Version', 'X-Env']
  121. )
  122. app.register_blueprint(web_bp)
  123. CORS(console_app_bp,
  124. resources={
  125. r"/*": {"origins": app.config['CONSOLE_CORS_ALLOW_ORIGINS']}},
  126. supports_credentials=True,
  127. allow_headers=['Content-Type', 'Authorization'],
  128. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  129. expose_headers=['X-Version', 'X-Env']
  130. )
  131. app.register_blueprint(console_app_bp)
  132. # create app
  133. app = create_app()
  134. celery = app.extensions["celery"]
  135. if app.config['TESTING']:
  136. print("App is running in TESTING mode")
  137. @app.after_request
  138. def after_request(response):
  139. """Add Version headers to the response."""
  140. response.headers.add('X-Version', app.config['CURRENT_VERSION'])
  141. response.headers.add('X-Env', app.config['DEPLOY_ENV'])
  142. return response
  143. @app.route('/health')
  144. def health():
  145. return Response(json.dumps({
  146. 'status': 'ok',
  147. 'version': app.config['CURRENT_VERSION']
  148. }), status=200, content_type="application/json")
  149. @app.route('/threads')
  150. def threads():
  151. num_threads = threading.active_count()
  152. threads = threading.enumerate()
  153. thread_list = []
  154. for thread in threads:
  155. thread_name = thread.name
  156. thread_id = thread.ident
  157. is_alive = thread.is_alive()
  158. thread_list.append({
  159. 'name': thread_name,
  160. 'id': thread_id,
  161. 'is_alive': is_alive
  162. })
  163. return {
  164. 'thread_num': num_threads,
  165. 'threads': thread_list
  166. }
  167. if __name__ == '__main__':
  168. app.run(host='0.0.0.0', port=5001)