dify/api/app.py

112 lines
2.5 KiB
Python
Raw Normal View History

2023-05-15 08:51:32 +08:00
import os
import sys
from configs import dify_config
if not dify_config.DEBUG:
2023-05-15 08:51:32 +08:00
from gevent import monkey
2024-04-12 14:53:44 +08:00
2023-05-15 08:51:32 +08:00
monkey.patch_all()
2024-04-25 22:26:45 +08:00
import grpc.experimental.gevent
2024-04-12 14:53:44 +08:00
grpc.experimental.gevent.init_gevent()
2023-05-15 08:51:32 +08:00
import json
import threading
import time
import warnings
2023-05-15 08:51:32 +08:00
2024-10-18 08:23:36 +08:00
from flask import Response
2024-10-18 08:23:36 +08:00
from app_factory import create_app
# DO NOT REMOVE BELOW
from events import event_handlers # noqa: F401
from extensions.ext_database import db
2024-07-04 18:18:26 +08:00
# TODO: Find a way to avoid importing models here
from models import account, dataset, model, source, task, tool, tools, web # noqa: F401
2024-04-12 14:53:44 +08:00
2023-05-15 08:51:32 +08:00
# DO NOT REMOVE ABOVE
if sys.version_info[:2] == (3, 10):
print("Warning: Python 3.10 will not be supported in the next version.")
2023-05-15 08:51:32 +08:00
warnings.simplefilter("ignore", ResourceWarning)
os.environ["TZ"] = "UTC"
# windows platform not support tzset
if hasattr(time, "tzset"):
time.tzset()
2023-05-15 08:51:32 +08:00
# create app
app = create_app()
celery = app.extensions["celery"]
if dify_config.TESTING:
2023-05-15 08:51:32 +08:00
print("App is running in TESTING mode")
@app.after_request
def after_request(response):
"""Add Version headers to the response."""
response.headers.add("X-Version", dify_config.CURRENT_VERSION)
response.headers.add("X-Env", dify_config.DEPLOY_ENV)
2023-05-15 08:51:32 +08:00
return response
@app.route("/health")
2023-05-15 08:51:32 +08:00
def health():
return Response(
json.dumps({"pid": os.getpid(), "status": "ok", "version": dify_config.CURRENT_VERSION}),
status=200,
content_type="application/json",
)
2023-05-15 08:51:32 +08:00
@app.route("/threads")
2023-05-15 08:51:32 +08:00
def threads():
num_threads = threading.active_count()
threads = threading.enumerate()
thread_list = []
for thread in threads:
thread_name = thread.name
thread_id = thread.ident
is_alive = thread.is_alive()
thread_list.append(
{
"name": thread_name,
"id": thread_id,
"is_alive": is_alive,
}
)
2023-05-15 08:51:32 +08:00
return {
"pid": os.getpid(),
"thread_num": num_threads,
"threads": thread_list,
2023-05-15 08:51:32 +08:00
}
@app.route("/db-pool-stat")
def pool_stat():
engine = db.engine
return {
"pid": os.getpid(),
"pool_size": engine.pool.size(),
"checked_in_connections": engine.pool.checkedin(),
"checked_out_connections": engine.pool.checkedout(),
"overflow_connections": engine.pool.overflow(),
"connection_timeout": engine.pool.timeout(),
"recycle_time": db.engine.pool._recycle,
}
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5001)