app.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. # -*- coding:utf-8 -*-
  2. import os
  3. from datetime import datetime
  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, session
  11. import flask_login
  12. from flask_cors import CORS
  13. from extensions import ext_session, ext_celery, ext_sentry, ext_redis, ext_login, ext_migrate, \
  14. ext_database, ext_storage
  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
  19. from events import event_handlers
  20. # DO NOT REMOVE ABOVE
  21. import core
  22. from config import Config, CloudEditionConfig
  23. from commands import register_commands
  24. from models.account import TenantAccountJoin
  25. from models.model import Account, EndUser, App
  26. import warnings
  27. warnings.simplefilter("ignore", ResourceWarning)
  28. class DifyApp(Flask):
  29. pass
  30. # -------------
  31. # Configuration
  32. # -------------
  33. config_type = os.getenv('EDITION', default='SELF_HOSTED') # ce edition first
  34. # ----------------------------
  35. # Application Factory Function
  36. # ----------------------------
  37. def create_app(test_config=None) -> Flask:
  38. app = DifyApp(__name__)
  39. if test_config:
  40. app.config.from_object(test_config)
  41. else:
  42. if config_type == "CLOUD":
  43. app.config.from_object(CloudEditionConfig())
  44. else:
  45. app.config.from_object(Config())
  46. app.secret_key = app.config['SECRET_KEY']
  47. logging.basicConfig(level=app.config.get('LOG_LEVEL', 'INFO'))
  48. initialize_extensions(app)
  49. register_blueprints(app)
  50. register_commands(app)
  51. core.init_app(app)
  52. return app
  53. def initialize_extensions(app):
  54. # Since the application instance is now created, pass it to each Flask
  55. # extension instance to bind it to the Flask application instance (app)
  56. ext_database.init_app(app)
  57. ext_migrate.init(app, db)
  58. ext_redis.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. account.last_active_at = datetime.utcnow()
  97. db.session.commit()
  98. # Log in the user with the updated user_id
  99. flask_login.login_user(account, remember=True)
  100. return account
  101. else:
  102. return None
  103. @login_manager.unauthorized_handler
  104. def unauthorized_handler():
  105. """Handle unauthorized requests."""
  106. return Response(json.dumps({
  107. 'code': 'unauthorized',
  108. 'message': "Unauthorized."
  109. }), status=401, content_type="application/json")
  110. # register blueprint routers
  111. def register_blueprints(app):
  112. from controllers.service_api import bp as service_api_bp
  113. from controllers.web import bp as web_bp
  114. from controllers.console import bp as console_app_bp
  115. app.register_blueprint(service_api_bp)
  116. CORS(web_bp,
  117. resources={
  118. r"/*": {"origins": app.config['WEB_API_CORS_ALLOW_ORIGINS']}},
  119. supports_credentials=True,
  120. allow_headers=['Content-Type', 'Authorization'],
  121. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  122. expose_headers=['X-Version', 'X-Env']
  123. )
  124. app.register_blueprint(web_bp)
  125. CORS(console_app_bp,
  126. resources={
  127. r"/*": {"origins": app.config['CONSOLE_CORS_ALLOW_ORIGINS']}},
  128. supports_credentials=True,
  129. allow_headers=['Content-Type', 'Authorization'],
  130. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  131. expose_headers=['X-Version', 'X-Env']
  132. )
  133. app.register_blueprint(console_app_bp)
  134. # create app
  135. app = create_app()
  136. celery = app.extensions["celery"]
  137. if app.config['TESTING']:
  138. print("App is running in TESTING mode")
  139. @app.after_request
  140. def after_request(response):
  141. """Add Version headers to the response."""
  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. if __name__ == '__main__':
  170. app.run(host='0.0.0.0', port=5001)