app.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. # -*- coding:utf-8 -*-
  2. import os
  3. from datetime import datetime, timedelta
  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. current_time = datetime.utcnow()
  113. # update last_active_at when last_active_at is more than 10 minutes ago
  114. if current_time - account.last_active_at > timedelta(minutes=10):
  115. account.last_active_at = current_time
  116. db.session.commit()
  117. # Log in the user with the updated user_id
  118. flask_login.login_user(account, remember=True)
  119. return account
  120. else:
  121. return None
  122. @login_manager.unauthorized_handler
  123. def unauthorized_handler():
  124. """Handle unauthorized requests."""
  125. return Response(json.dumps({
  126. 'code': 'unauthorized',
  127. 'message': "Unauthorized."
  128. }), status=401, content_type="application/json")
  129. # register blueprint routers
  130. def register_blueprints(app):
  131. from controllers.service_api import bp as service_api_bp
  132. from controllers.web import bp as web_bp
  133. from controllers.console import bp as console_app_bp
  134. CORS(service_api_bp,
  135. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  136. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH']
  137. )
  138. app.register_blueprint(service_api_bp)
  139. CORS(web_bp,
  140. resources={
  141. r"/*": {"origins": app.config['WEB_API_CORS_ALLOW_ORIGINS']}},
  142. supports_credentials=True,
  143. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  144. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  145. expose_headers=['X-Version', 'X-Env']
  146. )
  147. app.register_blueprint(web_bp)
  148. CORS(console_app_bp,
  149. resources={
  150. r"/*": {"origins": app.config['CONSOLE_CORS_ALLOW_ORIGINS']}},
  151. supports_credentials=True,
  152. allow_headers=['Content-Type', 'Authorization'],
  153. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  154. expose_headers=['X-Version', 'X-Env']
  155. )
  156. app.register_blueprint(console_app_bp)
  157. # create app
  158. app = create_app()
  159. celery = app.extensions["celery"]
  160. if app.config['TESTING']:
  161. print("App is running in TESTING mode")
  162. @app.after_request
  163. def after_request(response):
  164. """Add Version headers to the response."""
  165. response.headers.add('X-Version', app.config['CURRENT_VERSION'])
  166. response.headers.add('X-Env', app.config['DEPLOY_ENV'])
  167. return response
  168. @app.route('/health')
  169. def health():
  170. return Response(json.dumps({
  171. 'status': 'ok',
  172. 'version': app.config['CURRENT_VERSION']
  173. }), status=200, content_type="application/json")
  174. @app.route('/threads')
  175. def threads():
  176. num_threads = threading.active_count()
  177. threads = threading.enumerate()
  178. thread_list = []
  179. for thread in threads:
  180. thread_name = thread.name
  181. thread_id = thread.ident
  182. is_alive = thread.is_alive()
  183. thread_list.append({
  184. 'name': thread_name,
  185. 'id': thread_id,
  186. 'is_alive': is_alive
  187. })
  188. return {
  189. 'thread_num': num_threads,
  190. 'threads': thread_list
  191. }
  192. @app.route('/db-pool-stat')
  193. def pool_stat():
  194. engine = db.engine
  195. return {
  196. 'pool_size': engine.pool.size(),
  197. 'checked_in_connections': engine.pool.checkedin(),
  198. 'checked_out_connections': engine.pool.checkedout(),
  199. 'overflow_connections': engine.pool.overflow(),
  200. 'connection_timeout': engine.pool.timeout(),
  201. 'recycle_time': db.engine.pool._recycle
  202. }
  203. if __name__ == '__main__':
  204. app.run(host='0.0.0.0', port=5001)