app.py 6.9 KB

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