app.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  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
  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. import warnings
  28. warnings.simplefilter("ignore", ResourceWarning)
  29. class DifyApp(Flask):
  30. pass
  31. # -------------
  32. # Configuration
  33. # -------------
  34. config_type = os.getenv('EDITION', default='SELF_HOSTED') # ce edition first
  35. # ----------------------------
  36. # Application Factory Function
  37. # ----------------------------
  38. def create_app(test_config=None) -> Flask:
  39. app = DifyApp(__name__)
  40. if test_config:
  41. app.config.from_object(test_config)
  42. else:
  43. if config_type == "CLOUD":
  44. app.config.from_object(CloudEditionConfig())
  45. else:
  46. app.config.from_object(Config())
  47. app.secret_key = app.config['SECRET_KEY']
  48. logging.basicConfig(level=app.config.get('LOG_LEVEL', 'INFO'))
  49. initialize_extensions(app)
  50. register_blueprints(app)
  51. register_commands(app)
  52. core.init_app(app)
  53. return app
  54. def initialize_extensions(app):
  55. # Since the application instance is now created, pass it to each Flask
  56. # extension instance to bind it to the Flask application instance (app)
  57. ext_database.init_app(app)
  58. ext_migrate.init(app, db)
  59. ext_redis.init_app(app)
  60. ext_storage.init_app(app)
  61. ext_celery.init_app(app)
  62. ext_session.init_app(app)
  63. ext_login.init_app(app)
  64. ext_mail.init_app(app)
  65. ext_sentry.init_app(app)
  66. # Flask-Login configuration
  67. @login_manager.user_loader
  68. def load_user(user_id):
  69. """Load user based on the user_id."""
  70. if request.blueprint == 'console':
  71. # Check if the user_id contains a dot, indicating the old format
  72. if '.' in user_id:
  73. tenant_id, account_id = user_id.split('.')
  74. else:
  75. account_id = user_id
  76. account = db.session.query(Account).filter(Account.id == account_id).first()
  77. if account:
  78. if account.status == AccountStatus.BANNED.value or account.status == AccountStatus.CLOSED.value:
  79. raise Forbidden('Account is banned or closed.')
  80. workspace_id = session.get('workspace_id')
  81. if workspace_id:
  82. tenant_account_join = db.session.query(TenantAccountJoin).filter(
  83. TenantAccountJoin.account_id == account.id,
  84. TenantAccountJoin.tenant_id == workspace_id
  85. ).first()
  86. if not tenant_account_join:
  87. tenant_account_join = db.session.query(TenantAccountJoin).filter(
  88. TenantAccountJoin.account_id == account.id).first()
  89. if tenant_account_join:
  90. account.current_tenant_id = tenant_account_join.tenant_id
  91. session['workspace_id'] = account.current_tenant_id
  92. else:
  93. account.current_tenant_id = workspace_id
  94. else:
  95. tenant_account_join = db.session.query(TenantAccountJoin).filter(
  96. TenantAccountJoin.account_id == account.id).first()
  97. if tenant_account_join:
  98. account.current_tenant_id = tenant_account_join.tenant_id
  99. session['workspace_id'] = account.current_tenant_id
  100. account.last_active_at = datetime.utcnow()
  101. db.session.commit()
  102. # Log in the user with the updated user_id
  103. flask_login.login_user(account, remember=True)
  104. return account
  105. else:
  106. return None
  107. @login_manager.unauthorized_handler
  108. def unauthorized_handler():
  109. """Handle unauthorized requests."""
  110. return Response(json.dumps({
  111. 'code': 'unauthorized',
  112. 'message': "Unauthorized."
  113. }), status=401, content_type="application/json")
  114. # register blueprint routers
  115. def register_blueprints(app):
  116. from controllers.service_api import bp as service_api_bp
  117. from controllers.web import bp as web_bp
  118. from controllers.console import bp as console_app_bp
  119. CORS(service_api_bp,
  120. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  121. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH']
  122. )
  123. app.register_blueprint(service_api_bp)
  124. CORS(web_bp,
  125. resources={
  126. r"/*": {"origins": app.config['WEB_API_CORS_ALLOW_ORIGINS']}},
  127. supports_credentials=True,
  128. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  129. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  130. expose_headers=['X-Version', 'X-Env']
  131. )
  132. app.register_blueprint(web_bp)
  133. CORS(console_app_bp,
  134. resources={
  135. r"/*": {"origins": app.config['CONSOLE_CORS_ALLOW_ORIGINS']}},
  136. supports_credentials=True,
  137. allow_headers=['Content-Type', 'Authorization'],
  138. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  139. expose_headers=['X-Version', 'X-Env']
  140. )
  141. app.register_blueprint(console_app_bp)
  142. # create app
  143. app = create_app()
  144. celery = app.extensions["celery"]
  145. if app.config['TESTING']:
  146. print("App is running in TESTING mode")
  147. @app.after_request
  148. def after_request(response):
  149. """Add Version headers to the response."""
  150. response.headers.add('X-Version', app.config['CURRENT_VERSION'])
  151. response.headers.add('X-Env', app.config['DEPLOY_ENV'])
  152. return response
  153. @app.route('/health')
  154. def health():
  155. return Response(json.dumps({
  156. 'status': 'ok',
  157. 'version': app.config['CURRENT_VERSION']
  158. }), status=200, content_type="application/json")
  159. @app.route('/threads')
  160. def threads():
  161. num_threads = threading.active_count()
  162. threads = threading.enumerate()
  163. thread_list = []
  164. for thread in threads:
  165. thread_name = thread.name
  166. thread_id = thread.ident
  167. is_alive = thread.is_alive()
  168. thread_list.append({
  169. 'name': thread_name,
  170. 'id': thread_id,
  171. 'is_alive': is_alive
  172. })
  173. return {
  174. 'thread_num': num_threads,
  175. 'threads': thread_list
  176. }
  177. if __name__ == '__main__':
  178. app.run(host='0.0.0.0', port=5001)