一、项目背景
本文分享一个基于 fastmcp 框架实现的文档处理服务,可实现 word 文档(.docx)与 json 数据格式的双向转换。通过此服务,开发者可以轻松实现文档内容提取、结构化数据填充、样式模板复用等功能,适用于自动化报告生成、数据导入导出等场景。
二、核心代码解析
1. 服务端实现(my_server.py)
import json from fastmcp import fastmcp from wan_neng_copy_word import clone_document as word_to_dict from wan_neng_copy_word_pro import clone_document from wan_neng_copy_word import clone_document as get_para_style from gen_all_styles import gen_all_styles mcp = fastmcp(name="myserver") # 基础问候工具 @mcp.tool def greet(name: str) -> str: """greet a user by name.""" return f"hello, {name}!" # word 转 json 工具 @mcp.tool def word_to_json(word_path: str) -> str: """convert a word document to json.""" body_s, body_p = word_to_dict(word_path) return json.dumps(body_p) # json 转 word 工具 @mcp.tool def json_to_word(word_path: str, json_data: str) -> str: """convert a json to word document.""" try: body_ws, _ = get_para_style('demo_template.docx') except: gen_all_styles() body_ws, _ = get_para_style('demo_template.docx') body_s, _ = get_para_style(word_path) clone_document(body_s, json.loads(json_data), body_ws, 'cloned_example.docx') return 'cloned_example.docx' # 启动 mcp 服务 if __name__ == "__main__": mcp.run(transport="streamable-http", host="127.0.0.1", port=9000)
关键组件说明:
- fastmcp:基于 mcp 协议的服务框架,提供工具注册与调用能力
- wan_neng_copy_word 系列模块:实现 word 文档解析与生成的核心逻辑
- gen_all_styles:样式模板生成工具
- 双向转换逻辑:
word_to_json
:提取文档内容结构并序列化为 jsonjson_to_word
:应用模板样式生成新文档
2. 客户端测试代码
import asyncio from fastmcp import client # mcp 服务配置 config = { "mcpservers": { "document-service": { "url": "http://127.0.0.1:9000/mcp", "transport": "streamable-http" } } } # 创建客户端实例 client = client(config) async def main(): async with client: # 读取 json 数据 with open("1.json", "r", encoding="utf-8") as f: body_p = f.read() # 调用 json 转 word 工具 result = await client.call_tool( "json_to_word", {"word_path": "1.docx", "json_data": body_p} ) print(f"生成文档路径: {result}") if __name__ == "__main__": asyncio.run(main())
三、运行环境要求
- python 3.8+ 环境
- 依赖库安装:
pip install fastmcp python-docx
- 文件依赖:
demo_template.docx
(样式模板)1.docx
(输入文档)1.json
(结构化数据)
四、功能演示流程
启动服务:
python my_server.py
执行客户端测试:
python client_test.py
- 输出结果:
- 生成
cloned_example.docx
文档 - 验证文档内容与原始模板样式的一致性
- 生成
五、应用场景
- 自动化报告生成:通过 api 动态填充数据到预设模板
- 文档结构分析:提取 word 内容进行 nlp 处理
- 跨格式转换:作为其他格式(如 markdown、html)转换的中间层
- 样式统一管理:基于模板批量生成标准化文档
六、注意事项
- 文件路径问题:确保工作目录包含所需模板文件
- 异常处理增强建议:
# 可扩展的异常处理示例 try: # 文件操作代码 except filenotfounderror as e: return {"error": f"missing file: {str(e)}"} except json.jsondecodeerror: return {"error": "invalid json input"}
- 性能优化方向:
- 添加缓存机制复用样式模板
- 支持异步文件读写
- 实现流式传输处理大文件
七、扩展建议
添加文件校验模块:
def validate_word_file(path): if not os.path.exists(path): raise valueerror("template file not found") if not path.endswith('.docx'): raise valueerror("invalid file format")
支持更多格式转换:
- 集成
pandoc
实现多格式转换 - 添加 pdf 导出功能
api 接口增强:
- 添加文件上传下载接口
- 实现任务队列异步处理
该实现展示了如何通过 mcp 协议构建文档处理服务,开发者可根据实际需求扩展更多文档操作功能。完整项目代码需注意分离服务端/客户端模块,并完善错误处理机制。
以上就是python使用fastmcp实现word文档与json数据互转的详细内容,更多关于python word与json互转的资料请关注代码网其它相关文章!
发表评论