app.py 7.2 KB

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