多彩编程 多彩编程MZPH · CODE BLOG
ARTICLE DETAIL

文章详情

深耕前端与后端开发技术的一线实战笔记与踩坑复盘。

Taipy REST 入门指南:基于 Taipy Core 的自动化 REST API 服务

Taipy REST 入门指南:基于 Taipy Core 的自动化 REST API 服务 Taipy REST 入门指南基于 Taipy Core 的自动化 REST API 服务【免费下载链接】taipyTurns Data and AI algorithms into production-ready web applications in no time.项目地址: https://gitcode.com/GitHub_Trending/ta/taipyTaipy REST 是构建在 Taipy Core 之上的 REST API 服务层它将 DataNodes、Tasks、Jobs、Sequences、Scenarios 与 Cycles 六大核心模块的操作封装为可编程调用的 HTTP 接口让外部系统能够通过 REST 调用自动化执行基于 Taipy 构建的业务流程。读完本文你将掌握 taipy-rest 的安装、配置、多方式部署Flask/Docker/Gunicorn/uWSGI/Heroku、完整 API 端点清单及实际调用示例并理解其 Flask 应用工厂与 APISpec 文档体系背后的源码实现。Taipy REST 是什么Taipy 是一个用于创建业务应用Business Applications的 Python 库被拆分为多个独立安装的包如taipy-core、taipy-rest让用户按需安装最少依赖。其中Taipy Core主要提供业务导向能力帮助用户创建和管理业务应用并通过时间、条件与假设hypothesis持续提升分析能力Taipy REST是 Avaiga 在taipy-core之上构建的一组 API作为 Taipy 的补充目标是通过 REST API 实现对 Taipy 流程的自动化。Taipy REST 提供了与 Taipy 全部模块交互的 REST API覆盖DataNodes数据节点Tasks任务Jobs作业Sequences序列Scenarios场景Cycles周期所有端点均挂载在/api/v1前缀下具体路由由 api/views.py 中的Blueprint(api, __name__, url_prefix/api/v1)定义。架构与源码结构Taipy REST 采用 Flask Flask-RESTful APISpec 构建核心源码位于 taipy/rest 目录其结构如下taipy/rest/api/端点与 Schema 定义。resources/所有与 Taipy 相关的端点实现DataNode、Task、Job、Sequence、Scenario、Cycle 各一个资源文件。schemas/Taipy 对象对应的 Schema用于数据的序列化marshalling与反序列化unmarshalling。views.py资源到 URL 的映射。taipy/rest/commons/整个应用共享的公共文件。templates/用于生成文档的 Swagger 与 ReDoc 模板。encoder.py自定义 JSON 编码器_CustomEncoder在应用工厂中被设置为RESTFUL_JSON的cls。pagination.py分页工具对应 APISpec 中注册的PaginatedResultSchema。to_from_model.py实体与模型之间的转换工具_to_model。taipy/rest/app.pyFlask 应用配置与创建应用工厂。taipy/rest/extensions.py应用工厂上使用的单例如apispec。taipy/rest/rest.py运行taipy-rest应用的主要 Python 入口。taipy/rest/config/rest_config.pyREST 服务的配置节定义。tests/rest/与taipy/rest/结构对应的单元测试。应用工厂create_appapp.py 中的create_app(testingFalse, flask_envNone, secret_keyNone)是标准 Flask 应用工厂app Flask(__name__) app.config.update( ENVos.getenv(FLASK_ENV, flask_env), TESTINGos.getenv(TESTING, testing), SECRET_KEYos.getenv(SECRET_KEY, secret_key), ) app.url_map.strict_slashes False app.config[RESTFUL_JSON] {cls: _CustomEncoder}工厂完成三件事配置应用环境、测试模式、密钥、JSON 编码器、调用configure_apispec(app)初始化 Swagger/OpenAPI 支持并注册PaginatedResult分页 Schema、通过register_blueprints(app)注册 API Blueprint。启动入口Rest 类rest.py 定义了可运行的Rest类其__init__从全局配置读取三个参数并创建 Flask 应用Config.global_config.testingbool是否以测试模式运行Config.global_config.envOptional[str]应用环境Config.global_config.secret_keyOptional[str]应用服务器密钥。这三个参数仅在高级场景下才需要修改默认行为即可满足标准与基础需求。run(**kwargs)方法会读取Config.rest中的port、host与ssl_context覆盖默认值后阻塞启动服务。安装最新稳定版taipy-rest可通过pip安装pip install taipy-rest安装开发版本通过 pip 与 git 从 taipy 仓库安装开发版本pip install githttps://gitgithub.com/Avaiga/taipy该命令会把包含全部依赖含taipy-rest包的taipy开发版本安装到当前 Python 环境中。如需获取taipy-rest源码进行学习或参与改进可克隆仓库克隆后taipy-rest源码位于taipy/rest目录git clone https://github.com/Avaiga/taipy.git运行前配置Taipy REST API 依赖 Taipy 配置对象的预配置——即必须事先定义 DataNodes、Tasks、Sequences 等所有配置包含这些配置的文件需要在运行时传给应用。需要定义的环境变量TAIPY_SETUP_FILE包含所有 Taipy 对象配置的文件的路径。若使用 Docker需要将存放该文件的目录以 volume 方式映射使其对应用可见。REST 服务自身的配置节除了TAIPY_SETUP_FILEREST 服务的监听参数由 rest_config.py 中的RestConfig定义可通过Config.configure_rest(...)配置参数默认值说明port5000REST 服务运行端口host127.0.0.1REST 服务运行主机use_httpsFalse是否对 REST 服务启用 HTTPSssl_certNoneSSL 证书文件路径ssl_keyNoneSSL 密钥文件路径从源码可见ssl_context属性在use_httpsTrue时返回(ssl_cert, ssl_key)元组并传给 Flask 的app.run()所有属性都经过_TemplateHandler._replace_templates处理支持模板变量替换。运行应用运行taipy-rest前需安装必需的开发包推荐使用 Pipenv 创建虚拟环境pip install pipenv pipenv install --dev本地运行flask runDocker 运行docker-compose up使用 Gunicorn 运行项目提供了简单的 WSGI 入口可用于 Gunicorn 或 uWSGI。Gunicorn 只需执行pip install gunicorn gunicorn myapi.wsgi:appGunicorn 随即运行在 8000 端口。如果选择 Gunicorn 作为 WSGI 服务器相应命令应写入 docker-compose 文件。使用 uWSGI 运行pip install uwsgi uwsgi --http 127.0.0.1:5000 --module myapi.wsgi:appuWSGI 随即运行在 5000 端口同样应把相应命令写入 docker-compose 文件。部署到 Heroku前提可用的 Docker 安装例如docker ps可执行且已登录 Herokuheroku login。# 登录容器注册表 heroku container:login # 创建 Heroku 应用 heroku create # 构建镜像并推送至 Container Registry heroku container:push web # 发布镜像 heroku container:release web发布完成后可通过heroku create返回的 URL 访问taipy-rest。API 端点总览所有端点均以/api/v1为前缀定义于 api/views.py。每个资源类都通过resource_class_kwargs{logger: _logger}注入共享日志器。DataNodes数据节点方法路径端点类说明GET/datanodes/datanode_id/DataNodeResource按 ID 获取数据节点不存在返回 404DELETE/datanodes/datanode_id/DataNodeResource按 ID 删除数据节点GET/datanodes/DataNodeList获取全部数据节点POST/datanodes/?config_idconfig_idDataNodeList依据 config_id 创建数据节点GET/datanodes/datanode_id/read/DataNodeReader读取数据节点中的数据支持过滤条件PUT/datanodes/datanode_id/write/DataNodeWriter将请求体数据写入数据节点Tasks任务方法路径端点类说明GET/tasks/task_id/TaskResource按 ID 获取任务DELETE/tasks/task_id/TaskResource按 ID 删除任务GET/tasks/TaskList获取全部任务POST/tasks/?config_idconfig_idTaskList依据 config_id 创建任务POST/tasks/submit/task_id/TaskExecutor提交执行任务Sequences序列方法路径端点类说明GET/sequences/sequence_id/SequenceResource按 ID 获取序列DELETE/sequences/sequence_id/SequenceResource按 ID 删除序列GET/sequences/SequenceList获取全部序列POST/sequences/?config_idconfig_idSequenceList依据 config_id 创建序列POST/sequences/submit/sequence_id/SequenceExecutor提交执行序列Scenarios场景方法路径端点类说明GET/scenarios/scenario_id/ScenarioResource按 ID 获取场景DELETE/scenarios/scenario_id/ScenarioResource按 ID 删除场景GET/scenarios/ScenarioList获取全部场景POST/scenarios/?config_idconfig_idScenarioList依据 config_id 创建场景POST/scenarios/submit/scenario_id/ScenarioExecutor提交执行场景Cycles周期方法路径端点类说明GET/cycles/cycle_id/CycleResource按 ID 获取周期DELETE/cycles/cycle_id/CycleResource按 ID 删除周期GET/cycles/CycleList获取全部周期POST/cycles/?config_idconfig_idCycleList依据 config_id 创建周期Jobs作业方法路径端点类说明GET/jobs/job_id/JobResource按 ID 获取作业DELETE/jobs/job_id/JobResource按 ID 删除作业GET/jobs/JobList获取全部作业POST/jobs/cancel/job_id/JobExecutor取消作业另外views.py 中的load_enterprise_resources(api)会在检测到企业版EnterpriseEdition._is_installed()时动态加载taipy.enterprise.rest.api.views的扩展资源社区版默认不加载。实际调用示例以下示例来自资源类源码中的 OpenAPI 文档注释resources/datanode.py服务默认运行于localhost:5000。获取单个数据节点curl -X GET http://localhost:5000/api/v1/datanodes/DATANODE_historical_data_set_9db1b542-2e45-44e7-8a85-03ef9ead173d成功响应示例省略部分字段{datanode: { id: DATANODE_historical_data_set_9db1b542-2e45-44e7-8a85-03ef9ead173d, config_id: historical_data_set, scope: Scope.SCENARIO: 2, storage_type: csv, name: Name of my historical data node, owner_id: SCENARIO_my_awesome_scenario_97f3fd67-8556-4c62-9b3b-ef189a599a38, last_edit_date: 2022-08-10T16:03:40.855082, job_ids: [], version: latest, validity_days: null, validity_seconds: null, edit_in_progress: false, data_node_properties: {path: daily-min-temperatures.csv, has_header: true} }}失败时返回 404{message:DataNode DATANODE_historical_data_set_9db1b542-2e45-44e7-8a85-03ef9ead173d not found}。Python 调用需安装requestsimport requests response requests.get( http://localhost:5000/api/v1/datanodes/DATANODE_historical_data_set_9db1b542-2e45-44e7-8a85-03ef9ead173d ) print(response) # Response [200] print(response.json())列出全部数据节点curl -X GET http://localhost:5000/api/v1/datanodes无数据节点时返回空数组[]。其实现datanode.py 中DataNodeList.get通过_DataManagerFactory._build_manager()._get_all()获取全部实体后以DataNodeSchema(manyTrue)序列化。创建数据节点curl -X POST http://localhost:5000/api/v1/datanodes?config_idhistorical_data_setconfig_id必须对应预先配置的DataNodeConfig否则抛出NonExistingDataNodeConfig并返回 404。创建成功返回 201 与数据节点配置信息{msg: datanode created, datanode: { default_path: null, path: daily-min-temperatures.csv, name: null, storage_type: csv, scope: 2, has_header: true} }从源码看DataNodeList.post通过ds_schema_map按storage_type选择对应 Schema支持csv、pickle、in_memory、sql_table、sql、mongo_collection、excel、generic、json九种存储类型再由manager._bulk_get_or_create({config})创建实例。读取数据节点curl -X GET \ http://localhost:5000/api/v1/datanodes/DATANODE_historical_data_set_9db1b542-2e45-44e7-8a85-03ef9ead173d/read对于存储类型为csv且未指定 exposed type 的数据节点数据以字典列表形式返回每个字典代表 CSV 文件的一行{data: [ {Date: 1981-01-01, Temp: 20.7}, {Date: 1981-01-02, Temp: 17.9}, {Date: 1981-01-03, Temp: 18.8}, {Date: 1981-01-04, Temp: 14.6}, {Date: 1981-01-05, Temp: 15.8} ]}该端点还支持在请求体中传入过滤条件DataNodeFilterSchema实现上会将{key, value, operator}列表转换为Operator枚举如EQUAL等后调用data_node.filter(operators)若结果为pd.DataFrame则转为to_dict(orientrecords)np.ndarray则转为列表。写入数据节点curl -X PUT -d [{path: /abc, type: 1}, {path: /def, type: 2}] \ -H Content-Type: application/json \ http://localhost:5000/api/v1/datanodes/DATANODE_my_config_75750ed8-4e09-4e00-958d-e352ee426cc9/writeDataNodeWriter.put读取请求体 JSON 后调用data_node.write(data)成功返回{message: Data node datanode_id was successfully written.}。删除数据节点curl -X DELETE \ http://localhost:5000/api/v1/datanodes/DATANODE_historical_data_set_9db1b542-2e45-44e7-8a85-03ef9ead173d成功返回{msg: datanode DATANODE_historical_data_set_9db1b542-2e45-44e7-8a85-03ef9ead173d deleted}不存在时返回 404。提交任务curl -X POST http://localhost:5000/api/v1/tasks/submit/TASK_my_config_75750ed8-4e09-4e00-958d-e352ee426cc9resources/task.py 中TaskExecutor.post通过_TaskManagerFactory._build_manager()._orchestrator().submit_task(task)将任务提交给 Taipy Core 编排器执行返回{message: Task task_id was submitted.}。API 文档与 OpenAPI运行应用后可通过以下地址访问自动生成的 API 文档/redoc-uiReDoc UI配置为读取 OpenAPI yaml 文件/openapi.yml以 yaml 格式返回 OpenAPI 规范文件。文档体系由 commons/apispec.py 的APISpecExt与 extensions.py 中注册的apispec单例提供。应用启动时views.py 的register_views()会逐一注册DataNodeSchema、TaskSchema、SequenceSchema、ScenarioSchema、CycleSchema、JobSchema及所有资源视图使每个端点含请求参数、响应码、响应 Schema都能在 Swagger/ReDoc 中完整呈现。权限说明从各资源类的 OpenAPI 注释可以看到Taipy Enterprise 版启用授权功能时不同端点要求不同角色读取类端点GET要求TAIPY_READER角色创建、删除、写入类端点POST/DELETE/PUT要求TAIPY_EDITOR角色提交/执行类端点如 submit要求TAIPY_EXECUTOR角色。社区版不启用该授权机制。小结Taipy REST 通过标准的 RESTful 接口将 Taipy Core 的业务编排能力对外开放配合TAIPY_SETUP_FILE配置与 Flask 生态的部署方式本地、Docker、Gunicorn、uWSGI、Heroku可以快速把 Taipy 场景接入外部调度系统、CI/CD 流水线或微服务架构。结合 taipy/rest 目录下的源码与 tests/rest 测试开发者可以深入理解其端点实现、Schema 序列化与文档生成机制并在此基础上扩展自定义端点。【免费下载链接】taipyTurns Data and AI algorithms into production-ready web applications in no time.项目地址: https://gitcode.com/GitHub_Trending/ta/taipy创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表