app_factory.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import logging
  2. import os
  3. import time
  4. from configs import dify_config
  5. from dify_app import DifyApp
  6. # ----------------------------
  7. # Application Factory Function
  8. # ----------------------------
  9. def create_flask_app_with_configs() -> DifyApp:
  10. """
  11. create a raw flask app
  12. with configs loaded from .env file
  13. """
  14. dify_app = DifyApp(__name__)
  15. dify_app.config.from_mapping(dify_config.model_dump())
  16. # populate configs into system environment variables
  17. for key, value in dify_app.config.items():
  18. if isinstance(value, str):
  19. os.environ[key] = value
  20. elif isinstance(value, int | float | bool):
  21. os.environ[key] = str(value)
  22. elif value is None:
  23. os.environ[key] = ""
  24. return dify_app
  25. def create_app() -> DifyApp:
  26. start_time = time.perf_counter()
  27. app = create_flask_app_with_configs()
  28. initialize_extensions(app)
  29. end_time = time.perf_counter()
  30. if dify_config.DEBUG:
  31. logging.info(f"Finished create_app ({round((end_time - start_time) * 1000, 2)} ms)")
  32. return app
  33. def initialize_extensions(app: DifyApp):
  34. from extensions import (
  35. ext_app_metrics,
  36. ext_blueprints,
  37. ext_celery,
  38. ext_code_based_extension,
  39. ext_commands,
  40. ext_compress,
  41. ext_database,
  42. ext_hosting_provider,
  43. ext_import_modules,
  44. ext_logging,
  45. ext_login,
  46. ext_mail,
  47. ext_migrate,
  48. ext_proxy_fix,
  49. ext_redis,
  50. ext_sentry,
  51. ext_set_secretkey,
  52. ext_storage,
  53. ext_timezone,
  54. ext_warnings,
  55. )
  56. extensions = [
  57. ext_timezone,
  58. ext_logging,
  59. ext_warnings,
  60. ext_import_modules,
  61. ext_set_secretkey,
  62. ext_compress,
  63. ext_code_based_extension,
  64. ext_database,
  65. ext_app_metrics,
  66. ext_migrate,
  67. ext_redis,
  68. ext_storage,
  69. ext_celery,
  70. ext_login,
  71. ext_mail,
  72. ext_hosting_provider,
  73. ext_sentry,
  74. ext_proxy_fix,
  75. ext_blueprints,
  76. ext_commands,
  77. ]
  78. for ext in extensions:
  79. short_name = ext.__name__.split(".")[-1]
  80. is_enabled = ext.is_enabled() if hasattr(ext, "is_enabled") else True
  81. if not is_enabled:
  82. if dify_config.DEBUG:
  83. logging.info(f"Skipped {short_name}")
  84. continue
  85. start_time = time.perf_counter()
  86. ext.init_app(app)
  87. end_time = time.perf_counter()
  88. if dify_config.DEBUG:
  89. logging.info(f"Loaded {short_name} ({round((end_time - start_time) * 1000, 2)} ms)")