app.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. import os
  2. from werkzeug.exceptions import Unauthorized
  3. if not os.environ.get("DEBUG") or os.environ.get("DEBUG").lower() != 'true':
  4. from gevent import monkey
  5. monkey.patch_all()
  6. # if os.environ.get("VECTOR_STORE") == 'milvus':
  7. import grpc.experimental.gevent
  8. grpc.experimental.gevent.init_gevent()
  9. import langchain
  10. langchain.verbose = True
  11. import json
  12. import logging
  13. import threading
  14. import time
  15. import warnings
  16. from flask import Flask, Response, request
  17. from flask_cors import CORS
  18. from commands import register_commands
  19. from config import CloudEditionConfig, Config
  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 services.account_service import AccountService
  37. # DO NOT REMOVE BELOW
  38. from events import event_handlers
  39. from models import account, dataset, model, source, task, tool, tools, web
  40. # DO NOT REMOVE ABOVE
  41. warnings.simplefilter("ignore", ResourceWarning)
  42. # fix windows platform
  43. if os.name == "nt":
  44. os.system('tzutil /s "UTC"')
  45. else:
  46. os.environ['TZ'] = 'UTC'
  47. time.tzset()
  48. class DifyApp(Flask):
  49. pass
  50. # -------------
  51. # Configuration
  52. # -------------
  53. config_type = os.getenv('EDITION', default='SELF_HOSTED') # ce edition first
  54. # ----------------------------
  55. # Application Factory Function
  56. # ----------------------------
  57. def create_app(test_config=None) -> Flask:
  58. app = DifyApp(__name__)
  59. if test_config:
  60. app.config.from_object(test_config)
  61. else:
  62. if config_type == "CLOUD":
  63. app.config.from_object(CloudEditionConfig())
  64. else:
  65. app.config.from_object(Config())
  66. app.secret_key = app.config['SECRET_KEY']
  67. logging.basicConfig(level=app.config.get('LOG_LEVEL', 'INFO'))
  68. initialize_extensions(app)
  69. register_blueprints(app)
  70. register_commands(app)
  71. return app
  72. def initialize_extensions(app):
  73. # Since the application instance is now created, pass it to each Flask
  74. # extension instance to bind it to the Flask application instance (app)
  75. ext_compress.init_app(app)
  76. ext_code_based_extension.init()
  77. ext_database.init_app(app)
  78. ext_migrate.init(app, db)
  79. ext_redis.init_app(app)
  80. ext_storage.init_app(app)
  81. ext_celery.init_app(app)
  82. ext_login.init_app(app)
  83. ext_mail.init_app(app)
  84. ext_hosting_provider.init_app(app)
  85. ext_sentry.init_app(app)
  86. # Flask-Login configuration
  87. @login_manager.request_loader
  88. def load_user_from_request(request_from_flask_login):
  89. """Load user based on the request."""
  90. if request.blueprint == 'console':
  91. # Check if the user_id contains a dot, indicating the old format
  92. auth_header = request.headers.get('Authorization', '')
  93. if not auth_header:
  94. auth_token = request.args.get('_token')
  95. if not auth_token:
  96. raise Unauthorized('Invalid Authorization token.')
  97. else:
  98. if ' ' not in auth_header:
  99. raise Unauthorized('Invalid Authorization header format. Expected \'Bearer <api-key>\' format.')
  100. auth_scheme, auth_token = auth_header.split(None, 1)
  101. auth_scheme = auth_scheme.lower()
  102. if auth_scheme != 'bearer':
  103. raise Unauthorized('Invalid Authorization header format. Expected \'Bearer <api-key>\' format.')
  104. decoded = PassportService().verify(auth_token)
  105. user_id = decoded.get('user_id')
  106. return AccountService.load_user(user_id)
  107. else:
  108. return None
  109. @login_manager.unauthorized_handler
  110. def unauthorized_handler():
  111. """Handle unauthorized requests."""
  112. return Response(json.dumps({
  113. 'code': 'unauthorized',
  114. 'message': "Unauthorized."
  115. }), status=401, content_type="application/json")
  116. # register blueprint routers
  117. def register_blueprints(app):
  118. from controllers.console import bp as console_app_bp
  119. from controllers.files import bp as files_bp
  120. from controllers.service_api import bp as service_api_bp
  121. from controllers.web import bp as web_bp
  122. CORS(service_api_bp,
  123. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  124. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH']
  125. )
  126. app.register_blueprint(service_api_bp)
  127. CORS(web_bp,
  128. resources={
  129. r"/*": {"origins": app.config['WEB_API_CORS_ALLOW_ORIGINS']}},
  130. supports_credentials=True,
  131. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  132. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  133. expose_headers=['X-Version', 'X-Env']
  134. )
  135. app.register_blueprint(web_bp)
  136. CORS(console_app_bp,
  137. resources={
  138. r"/*": {"origins": app.config['CONSOLE_CORS_ALLOW_ORIGINS']}},
  139. supports_credentials=True,
  140. allow_headers=['Content-Type', 'Authorization'],
  141. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  142. expose_headers=['X-Version', 'X-Env']
  143. )
  144. app.register_blueprint(console_app_bp)
  145. CORS(files_bp,
  146. allow_headers=['Content-Type'],
  147. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH']
  148. )
  149. app.register_blueprint(files_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)