app.py 8.2 KB

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