Prefect 是一种工作流编排工具,让开发人员能够构建、观察和应对数据管道。
它是将任何Python函数转化为可被观察和协调的工作单元的最简单方式。只需带上你的Python代码,添加几个装饰器,就可以使用了!
安装
# 建议在虚拟环境中使用比如 virtualenv pipenv poetry
pip install -U prefect
prefect --help
更多安装方法可以查看 Prefect官网
使用
开发一个简单的 flow
此处命名为 flow.py
import httpx
from prefect import flow
@flow
def get_repo_info():
url = "https://api.github.com/repos/PrefectHQ/prefect"
response = httpx.get(url)
response.raise_for_status()
repo = response.json()
print(f"PrefectHQ/prefect repository statistics 🤓:")
print(f"Stars 🌠 : {repo['stargazers_count']}")
print(f"Forks 🍴 : {repo['forks_count']}")
if __name__ == "__main__":
get_repo_info()
项目初始化
prefect init
此时只是测试选择 local
创建工作池
prefect work-pool create --type process local
local 是工作池的名称,可以按自己想法命名,此处定义为 local
启动工作池
prefect worker start --pool local
创建部署
新启动一个终端,上面的worker占用了一个终端
prefect deploy --name get_repo_info --pool local --cron '0 0 * * *' flow.py:get_repo_info
创建一个名称为 get_repo_info 的部署,每天 0 点 0 分执行
启动 WEB UI
prefect server start
打开 http://127.0.0.1:4200
点击 Deployments 就可以看到我们刚刚创建的 get_repo_info
Dashboard 可以查看任务的运行情况
用起来是不是比 crontab
方便很多。