app.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import os
  2. from configs import dify_config
  3. if os.environ.get("DEBUG", "false").lower() != 'true':
  4. from gevent import monkey
  5. monkey.patch_all()
  6. import grpc.experimental.gevent
  7. grpc.experimental.gevent.init_gevent()
  8. import json
  9. import logging
  10. import sys
  11. import threading
  12. import time
  13. import warnings
  14. from logging.handlers import RotatingFileHandler
  15. from flask import Flask, Response, request
  16. from flask_cors import CORS
  17. from werkzeug.exceptions import Unauthorized
  18. from commands import register_commands
  19. # DO NOT REMOVE BELOW
  20. from events import event_handlers
  21. from extensions import (
  22. ext_celery,
  23. ext_code_based_extension,
  24. ext_compress,
  25. ext_database,
  26. ext_hosting_provider,
  27. ext_login,
  28. ext_mail,
  29. ext_migrate,
  30. ext_redis,
  31. ext_sentry,
  32. ext_storage,
  33. )
  34. from extensions.ext_database import db
  35. from extensions.ext_login import login_manager
  36. from libs.passport import PassportService
  37. # TODO: Find a way to avoid importing models here
  38. from models import account, dataset, model, source, task, tool, tools, web
  39. from services.account_service import AccountService
  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_flask_app_with_configs() -> Flask:
  58. """
  59. create a raw flask app
  60. with configs loaded from .env file
  61. """
  62. dify_app = DifyApp(__name__)
  63. dify_app.config.from_mapping(dify_config.model_dump())
  64. # populate configs into system environment variables
  65. for key, value in dify_app.config.items():
  66. if isinstance(value, str):
  67. os.environ[key] = value
  68. elif isinstance(value, int | float | bool):
  69. os.environ[key] = str(value)
  70. elif value is None:
  71. os.environ[key] = ''
  72. return dify_app
  73. def create_app() -> Flask:
  74. app = create_flask_app_with_configs()
  75. app.secret_key = app.config['SECRET_KEY']
  76. log_handlers = None
  77. log_file = app.config.get('LOG_FILE')
  78. if log_file:
  79. log_dir = os.path.dirname(log_file)
  80. os.makedirs(log_dir, exist_ok=True)
  81. log_handlers = [
  82. RotatingFileHandler(
  83. filename=log_file,
  84. maxBytes=1024 * 1024 * 1024,
  85. backupCount=5
  86. ),
  87. logging.StreamHandler(sys.stdout)
  88. ]
  89. logging.basicConfig(
  90. level=app.config.get('LOG_LEVEL'),
  91. format=app.config.get('LOG_FORMAT'),
  92. datefmt=app.config.get('LOG_DATEFORMAT'),
  93. handlers=log_handlers,
  94. force=True
  95. )
  96. log_tz = app.config.get('LOG_TZ')
  97. if log_tz:
  98. from datetime import datetime
  99. import pytz
  100. timezone = pytz.timezone(log_tz)
  101. def time_converter(seconds):
  102. return datetime.utcfromtimestamp(seconds).astimezone(timezone).timetuple()
  103. for handler in logging.root.handlers:
  104. handler.formatter.converter = time_converter
  105. initialize_extensions(app)
  106. register_blueprints(app)
  107. register_commands(app)
  108. return app
  109. def initialize_extensions(app):
  110. # Since the application instance is now created, pass it to each Flask
  111. # extension instance to bind it to the Flask application instance (app)
  112. ext_compress.init_app(app)
  113. ext_code_based_extension.init()
  114. ext_database.init_app(app)
  115. ext_migrate.init(app, db)
  116. ext_redis.init_app(app)
  117. ext_storage.init_app(app)
  118. ext_celery.init_app(app)
  119. ext_login.init_app(app)
  120. ext_mail.init_app(app)
  121. ext_hosting_provider.init_app(app)
  122. ext_sentry.init_app(app)
  123. # Flask-Login configuration
  124. @login_manager.request_loader
  125. def load_user_from_request(request_from_flask_login):
  126. """Load user based on the request."""
  127. if request.blueprint not in ['console', 'inner_api']:
  128. return None
  129. # Check if the user_id contains a dot, indicating the old format
  130. auth_header = request.headers.get('Authorization', '')
  131. if not auth_header:
  132. auth_token = request.args.get('_token')
  133. if not auth_token:
  134. raise Unauthorized('Invalid Authorization token.')
  135. else:
  136. if ' ' not in auth_header:
  137. raise Unauthorized('Invalid Authorization header format. Expected \'Bearer <api-key>\' format.')
  138. auth_scheme, auth_token = auth_header.split(None, 1)
  139. auth_scheme = auth_scheme.lower()
  140. if auth_scheme != 'bearer':
  141. raise Unauthorized('Invalid Authorization header format. Expected \'Bearer <api-key>\' format.')
  142. decoded = PassportService().verify(auth_token)
  143. user_id = decoded.get('user_id')
  144. return AccountService.load_logged_in_account(account_id=user_id, token=auth_token)
  145. @login_manager.unauthorized_handler
  146. def unauthorized_handler():
  147. """Handle unauthorized requests."""
  148. return Response(json.dumps({
  149. 'code': 'unauthorized',
  150. 'message': "Unauthorized."
  151. }), status=401, content_type="application/json")
  152. # register blueprint routers
  153. def register_blueprints(app):
  154. from controllers.console import bp as console_app_bp
  155. from controllers.files import bp as files_bp
  156. from controllers.inner_api import bp as inner_api_bp
  157. from controllers.service_api import bp as service_api_bp
  158. from controllers.web import bp as web_bp
  159. CORS(service_api_bp,
  160. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  161. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH']
  162. )
  163. app.register_blueprint(service_api_bp)
  164. CORS(web_bp,
  165. resources={
  166. r"/*": {"origins": app.config['WEB_API_CORS_ALLOW_ORIGINS']}},
  167. supports_credentials=True,
  168. allow_headers=['Content-Type', 'Authorization', 'X-App-Code'],
  169. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  170. expose_headers=['X-Version', 'X-Env']
  171. )
  172. app.register_blueprint(web_bp)
  173. CORS(console_app_bp,
  174. resources={
  175. r"/*": {"origins": app.config['CONSOLE_CORS_ALLOW_ORIGINS']}},
  176. supports_credentials=True,
  177. allow_headers=['Content-Type', 'Authorization'],
  178. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH'],
  179. expose_headers=['X-Version', 'X-Env']
  180. )
  181. app.register_blueprint(console_app_bp)
  182. CORS(files_bp,
  183. allow_headers=['Content-Type'],
  184. methods=['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS', 'PATCH']
  185. )
  186. app.register_blueprint(files_bp)
  187. app.register_blueprint(inner_api_bp)
  188. # create app
  189. app = create_app()
  190. celery = app.extensions["celery"]
  191. if app.config.get('TESTING'):
  192. print("App is running in TESTING mode")
  193. @app.after_request
  194. def after_request(response):
  195. """Add Version headers to the response."""
  196. response.set_cookie('remember_token', '', expires=0)
  197. response.headers.add('X-Version', app.config['CURRENT_VERSION'])
  198. response.headers.add('X-Env', app.config['DEPLOY_ENV'])
  199. return response
  200. @app.route('/health')
  201. def health():
  202. return Response(json.dumps({
  203. 'status': 'ok',
  204. 'version': app.config['CURRENT_VERSION']
  205. }), status=200, content_type="application/json")
  206. @app.route('/threads')
  207. def threads():
  208. num_threads = threading.active_count()
  209. threads = threading.enumerate()
  210. thread_list = []
  211. for thread in threads:
  212. thread_name = thread.name
  213. thread_id = thread.ident
  214. is_alive = thread.is_alive()
  215. thread_list.append({
  216. 'name': thread_name,
  217. 'id': thread_id,
  218. 'is_alive': is_alive
  219. })
  220. return {
  221. 'thread_num': num_threads,
  222. 'threads': thread_list
  223. }
  224. @app.route('/db-pool-stat')
  225. def pool_stat():
  226. engine = db.engine
  227. return {
  228. 'pool_size': engine.pool.size(),
  229. 'checked_in_connections': engine.pool.checkedin(),
  230. 'checked_out_connections': engine.pool.checkedout(),
  231. 'overflow_connections': engine.pool.overflow(),
  232. 'connection_timeout': engine.pool.timeout(),
  233. 'recycle_time': db.engine.pool._recycle
  234. }
  235. if __name__ == '__main__':
  236. app.run(host='0.0.0.0', port=5001)