app.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import os
  2. if not os.environ.get("DEBUG") or os.environ.get("DEBUG").lower() != 'true':
  3. from gevent import monkey
  4. monkey.patch_all()
  5. # if os.environ.get("VECTOR_STORE") == 'milvus':
  6. import grpc.experimental.gevent
  7. grpc.experimental.gevent.init_gevent()
  8. import json
  9. import logging
  10. import threading
  11. import time
  12. import warnings
  13. from flask import Flask, Response, request
  14. from flask_cors import CORS
  15. from werkzeug.exceptions import Unauthorized
  16. from commands import register_commands
  17. from config import CloudEditionConfig, Config
  18. # DO NOT REMOVE BELOW
  19. from events import event_handlers
  20. from extensions import (
  21. ext_celery,
  22. ext_code_based_extension,
  23. ext_compress,
  24. ext_database,
  25. ext_hosting_provider,
  26. ext_login,
  27. ext_mail,
  28. ext_migrate,
  29. ext_redis,
  30. ext_sentry,
  31. ext_storage,
  32. )
  33. from extensions.ext_database import db
  34. from extensions.ext_login import login_manager
  35. from libs.passport import PassportService
  36. from models import account, dataset, model, source, task, tool, tools, web
  37. from services.account_service import AccountService
  38. # DO NOT REMOVE ABOVE
  39. warnings.simplefilter("ignore", ResourceWarning)
  40. # fix windows platform
  41. if os.name == "nt":
  42. os.system('tzutil /s "UTC"')
  43. else:
  44. os.environ['TZ'] = 'UTC'
  45. time.tzset()
  46. class DifyApp(Flask):
  47. pass
  48. # -------------
  49. # Configuration
  50. # -------------
  51. config_type = os.getenv('EDITION', default='SELF_HOSTED') # ce edition first
  52. # ----------------------------
  53. # Application Factory Function
  54. # ----------------------------
  55. def create_app(test_config=None) -> Flask:
  56. app = DifyApp(__name__)
  57. if test_config:
  58. app.config.from_object(test_config)
  59. else:
  60. if config_type == "CLOUD":
  61. app.config.from_object(CloudEditionConfig())
  62. else:
  63. app.config.from_object(Config())
  64. app.secret_key = app.config['SECRET_KEY']
  65. logging.basicConfig(level=app.config.get('LOG_LEVEL', 'INFO'))
  66. initialize_extensions(app)
  67. register_blueprints(app)
  68. register_commands(app)
  69. return app
  70. def initialize_extensions(app):
  71. # Since the application instance is now created, pass it to each Flask
  72. # extension instance to bind it to the Flask application instance (app)
  73. ext_compress.init_app(app)
  74. ext_code_based_extension.init()
  75. ext_database.init_app(app)
  76. ext_migrate.init(app, db)
  77. ext_redis.init_app(app)
  78. ext_storage.init_app(app)
  79. ext_celery.init_app(app)
  80. ext_login.init_app(app)
  81. ext_mail.init_app(app)
  82. ext_hosting_provider.init_app(app)
  83. ext_sentry.init_app(app)
  84. # Flask-Login configuration
  85. @login_manager.request_loader
  86. def load_user_from_request(request_from_flask_login):
  87. """Load user based on the request."""
  88. if request.blueprint in ['console', 'inner_api']:
  89. # Check if the user_id contains a dot, indicating the old format
  90. auth_header = request.headers.get('Authorization', '')
  91. if not auth_header:
  92. auth_token = request.args.get('_token')
  93. if not auth_token:
  94. raise Unauthorized('Invalid Authorization token.')
  95. else:
  96. if ' ' not in auth_header:
  97. raise Unauthorized('Invalid Authorization header format. Expected \'Bearer <api-key>\' format.')
  98. auth_scheme, auth_token = auth_header.split(None, 1)
  99. auth_scheme = auth_scheme.lower()
  100. if auth_scheme != 'bearer':
  101. raise Unauthorized('Invalid Authorization header format. Expected \'Bearer <api-key>\' format.')
  102. decoded = PassportService().verify(auth_token)
  103. user_id = decoded.get('user_id')
  104. return AccountService.load_user(user_id)
  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.console import bp as console_app_bp
  117. from controllers.files import bp as files_bp
  118. from controllers.inner_api import bp as inner_api_bp
  119. from controllers.service_api import bp as service_api_bp
  120. from controllers.web import bp as web_bp
  121. CORS(service_api_bp,
  122. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  123. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH']
  124. )
  125. app.register_blueprint(service_api_bp)
  126. CORS(web_bp,
  127. resources={
  128. r"/*": {"origins": app.config['WEB_API_CORS_ALLOW_ORIGINS']}},
  129. supports_credentials=True,
  130. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  131. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  132. expose_headers=['X-Version', 'X-Env']
  133. )
  134. app.register_blueprint(web_bp)
  135. CORS(console_app_bp,
  136. resources={
  137. r"/*": {"origins": app.config['CONSOLE_CORS_ALLOW_ORIGINS']}},
  138. supports_credentials=True,
  139. allow_headers=['Content-Type', 'Authorization'],
  140. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  141. expose_headers=['X-Version', 'X-Env']
  142. )
  143. app.register_blueprint(console_app_bp)
  144. CORS(files_bp,
  145. allow_headers=['Content-Type'],
  146. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH']
  147. )
  148. app.register_blueprint(files_bp)
  149. app.register_blueprint(inner_api_bp)
  150. # create app
  151. app = create_app()
  152. celery = app.extensions["celery"]
  153. if app.config['TESTING']:
  154. print("App is running in TESTING mode")
  155. @app.after_request
  156. def after_request(response):
  157. """Add Version headers to the response."""
  158. response.set_cookie('remember_token', '', expires=0)
  159. response.headers.add('X-Version', app.config['CURRENT_VERSION'])
  160. response.headers.add('X-Env', app.config['DEPLOY_ENV'])
  161. return response
  162. @app.route('/health')
  163. def health():
  164. return Response(json.dumps({
  165. 'status': 'ok',
  166. 'version': app.config['CURRENT_VERSION']
  167. }), status=200, content_type="application/json")
  168. @app.route('/threads')
  169. def threads():
  170. num_threads = threading.active_count()
  171. threads = threading.enumerate()
  172. thread_list = []
  173. for thread in threads:
  174. thread_name = thread.name
  175. thread_id = thread.ident
  176. is_alive = thread.is_alive()
  177. thread_list.append({
  178. 'name': thread_name,
  179. 'id': thread_id,
  180. 'is_alive': is_alive
  181. })
  182. return {
  183. 'thread_num': num_threads,
  184. 'threads': thread_list
  185. }
  186. @app.route('/db-pool-stat')
  187. def pool_stat():
  188. engine = db.engine
  189. return {
  190. 'pool_size': engine.pool.size(),
  191. 'checked_in_connections': engine.pool.checkedin(),
  192. 'checked_out_connections': engine.pool.checkedout(),
  193. 'overflow_connections': engine.pool.overflow(),
  194. 'connection_timeout': engine.pool.timeout(),
  195. 'recycle_time': db.engine.pool._recycle
  196. }
  197. if __name__ == '__main__':
  198. app.run(host='0.0.0.0', port=5001)