app.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  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 core.model_providers.providers import hosted
  15. from extensions import ext_session, ext_celery, ext_sentry, ext_redis, ext_login, ext_migrate, \
  16. ext_database, ext_storage, ext_mail, ext_stripe
  17. from extensions.ext_database import db
  18. from extensions.ext_login import login_manager
  19. # DO NOT REMOVE BELOW
  20. from models import model, account, dataset, web, task, source, tool
  21. from events import event_handlers
  22. # DO NOT REMOVE ABOVE
  23. import core
  24. from config import Config, CloudEditionConfig
  25. from commands import register_commands
  26. from models.account import TenantAccountJoin, AccountStatus
  27. from models.model import Account, EndUser, App
  28. from services.account_service import TenantService
  29. import warnings
  30. warnings.simplefilter("ignore", ResourceWarning)
  31. class DifyApp(Flask):
  32. pass
  33. # -------------
  34. # Configuration
  35. # -------------
  36. config_type = os.getenv('EDITION', default='SELF_HOSTED') # ce edition first
  37. # ----------------------------
  38. # Application Factory Function
  39. # ----------------------------
  40. def create_app(test_config=None) -> Flask:
  41. app = DifyApp(__name__)
  42. if test_config:
  43. app.config.from_object(test_config)
  44. else:
  45. if config_type == "CLOUD":
  46. app.config.from_object(CloudEditionConfig())
  47. else:
  48. app.config.from_object(Config())
  49. app.secret_key = app.config['SECRET_KEY']
  50. logging.basicConfig(level=app.config.get('LOG_LEVEL', 'INFO'))
  51. initialize_extensions(app)
  52. register_blueprints(app)
  53. register_commands(app)
  54. hosted.init_app(app)
  55. return app
  56. def initialize_extensions(app):
  57. # Since the application instance is now created, pass it to each Flask
  58. # extension instance to bind it to the Flask application instance (app)
  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_session.init_app(app)
  65. ext_login.init_app(app)
  66. ext_mail.init_app(app)
  67. ext_sentry.init_app(app)
  68. ext_stripe.init_app(app)
  69. def _create_tenant_for_account(account):
  70. tenant = TenantService.create_tenant(f"{account.name}'s Workspace")
  71. TenantService.create_tenant_member(tenant, account, role='owner')
  72. account.current_tenant = tenant
  73. return tenant
  74. # Flask-Login configuration
  75. @login_manager.user_loader
  76. def load_user(user_id):
  77. """Load user based on the user_id."""
  78. if request.blueprint == 'console':
  79. # Check if the user_id contains a dot, indicating the old format
  80. if '.' in user_id:
  81. tenant_id, account_id = user_id.split('.')
  82. else:
  83. account_id = user_id
  84. account = db.session.query(Account).filter(Account.id == account_id).first()
  85. if account:
  86. if account.status == AccountStatus.BANNED.value or account.status == AccountStatus.CLOSED.value:
  87. raise Forbidden('Account is banned or closed.')
  88. workspace_id = session.get('workspace_id')
  89. if workspace_id:
  90. tenant_account_join = db.session.query(TenantAccountJoin).filter(
  91. TenantAccountJoin.account_id == account.id,
  92. TenantAccountJoin.tenant_id == workspace_id
  93. ).first()
  94. if not tenant_account_join:
  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. else:
  100. _create_tenant_for_account(account)
  101. session['workspace_id'] = account.current_tenant_id
  102. else:
  103. account.current_tenant_id = workspace_id
  104. else:
  105. tenant_account_join = db.session.query(TenantAccountJoin).filter(
  106. TenantAccountJoin.account_id == account.id).first()
  107. if tenant_account_join:
  108. account.current_tenant_id = tenant_account_join.tenant_id
  109. else:
  110. _create_tenant_for_account(account)
  111. session['workspace_id'] = account.current_tenant_id
  112. account.last_active_at = datetime.utcnow()
  113. db.session.commit()
  114. # Log in the user with the updated user_id
  115. flask_login.login_user(account, remember=True)
  116. return account
  117. else:
  118. return None
  119. @login_manager.unauthorized_handler
  120. def unauthorized_handler():
  121. """Handle unauthorized requests."""
  122. return Response(json.dumps({
  123. 'code': 'unauthorized',
  124. 'message': "Unauthorized."
  125. }), status=401, content_type="application/json")
  126. # register blueprint routers
  127. def register_blueprints(app):
  128. from controllers.service_api import bp as service_api_bp
  129. from controllers.web import bp as web_bp
  130. from controllers.console import bp as console_app_bp
  131. CORS(service_api_bp,
  132. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  133. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH']
  134. )
  135. app.register_blueprint(service_api_bp)
  136. CORS(web_bp,
  137. resources={
  138. r"/*": {"origins": app.config['WEB_API_CORS_ALLOW_ORIGINS']}},
  139. supports_credentials=True,
  140. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  141. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  142. expose_headers=['X-Version', 'X-Env']
  143. )
  144. app.register_blueprint(web_bp)
  145. CORS(console_app_bp,
  146. resources={
  147. r"/*": {"origins": app.config['CONSOLE_CORS_ALLOW_ORIGINS']}},
  148. supports_credentials=True,
  149. allow_headers=['Content-Type', 'Authorization'],
  150. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  151. expose_headers=['X-Version', 'X-Env']
  152. )
  153. app.register_blueprint(console_app_bp)
  154. # create app
  155. app = create_app()
  156. celery = app.extensions["celery"]
  157. if app.config['TESTING']:
  158. print("App is running in TESTING mode")
  159. @app.after_request
  160. def after_request(response):
  161. """Add Version headers to the response."""
  162. response.headers.add('X-Version', app.config['CURRENT_VERSION'])
  163. response.headers.add('X-Env', app.config['DEPLOY_ENV'])
  164. return response
  165. @app.route('/health')
  166. def health():
  167. return Response(json.dumps({
  168. 'status': 'ok',
  169. 'version': app.config['CURRENT_VERSION']
  170. }), status=200, content_type="application/json")
  171. @app.route('/threads')
  172. def threads():
  173. num_threads = threading.active_count()
  174. threads = threading.enumerate()
  175. thread_list = []
  176. for thread in threads:
  177. thread_name = thread.name
  178. thread_id = thread.ident
  179. is_alive = thread.is_alive()
  180. thread_list.append({
  181. 'name': thread_name,
  182. 'id': thread_id,
  183. 'is_alive': is_alive
  184. })
  185. return {
  186. 'thread_num': num_threads,
  187. 'threads': thread_list
  188. }
  189. @app.route('/db-pool-stat')
  190. def pool_stat():
  191. engine = db.engine
  192. return {
  193. 'pool_size': engine.pool.size(),
  194. 'checked_in_connections': engine.pool.checkedin(),
  195. 'checked_out_connections': engine.pool.checkedout(),
  196. 'overflow_connections': engine.pool.overflow(),
  197. 'connection_timeout': engine.pool.timeout(),
  198. 'recycle_time': db.engine.pool._recycle
  199. }
  200. if __name__ == '__main__':
  201. app.run(host='0.0.0.0', port=5001)