学习dify第四天-api
- 安装
- docker/entrypoint.sh
- 目录
- 入口类app.py
从web前篇介绍了docker的加载文件,api和web篇差不多,都是从跟目录的docker加载到项目的/api/Dockerfile然后加载的。
这里主要是flask框架,可以看之前写的flask框架的文章。
安装
api下的docker挺简单简单流程是:
使用了Debian中的python3.12构建了初始环境,使用poetry构建(比pip构建能减少冲突依赖),开5001的api端口,安装node和curl这些常用工具,拷贝python的环境.venv,执行docker/entrypoint.sh
COPY pyproject.toml poetry.lock ./
RUN poetry install --sync --no-cache --no-root
docker/entrypoint.sh
#!/bin/bashset -e
# 默认是镜像
if [[ "${MIGRATION_ENABLED}" == "true" ]]; thenecho "Running migrations"flask upgrade-db
fi
#区分是不是工作服务,默认是api,他俩用的一个包
if [[ "${MODE}" == "worker" ]]; then# Get the number of available CPU coresif [ "${CELERY_AUTO_SCALE,,}" = "true" ]; then# Set MAX_WORKERS to the number of available cores if not specifiedAVAILABLE_CORES=$(nproc)MAX_WORKERS=${CELERY_MAX_WORKERS:-$AVAILABLE_CORES}MIN_WORKERS=${CELERY_MIN_WORKERS:-1}CONCURRENCY_OPTION="--autoscale=${MAX_WORKERS},${MIN_WORKERS}"elseCONCURRENCY_OPTION="-c ${CELERY_WORKER_AMOUNT:-1}"fi
# 如果是worker服务,使用 celery开启任务队列,应用定义在 app/celery.py,使用gevent(并发池类型:基于协程,适合 I/O 密集型任务),默认消费dataset,mail,ops_trace,app_deletion队列exec celery -A app.celery worker -P ${CELERY_WORKER_CLASS:-gevent} $CONCURRENCY_OPTION --loglevel ${LOG_LEVEL:-INFO} \-Q ${CELERY_QUEUES:-dataset,mail,ops_trace,app_deletion}elif [[ "${MODE}" == "beat" ]]; then
# Celery Beat 是 Celery 的定时任务调度器,用于按照预设的时间表触发任务。Celery Beat 负责调度任务,但实际执行任务的是 Celery Worker。因此,需要同时运行 Celery Worker 来处理这些任务,没发现哪里设置beatexec celery -A app.celery beat --loglevel ${LOG_LEVEL:-INFO}
else
# 如果DEBUG为true就用flask启动,测试用,否则gunicorn启动,生产用if [[ "${DEBUG}" == "true" ]]; thenexec flask run --host=${DIFY_BIND_ADDRESS:-0.0.0.0} --port=${DIFY_PORT:-5001} --debugelse# 如果是api,那么指定app.py为入口类exec gunicorn \--bind "${DIFY_BIND_ADDRESS:-0.0.0.0}:${DIFY_PORT:-5001}" \--workers