app.py 6.8 KB

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