Files
ALL-teach_sys/frontend_视觉设计/add_attachments_to_mock.py

82 lines
3.3 KiB
Python
Raw Permalink Normal View History

#!/usr/bin/env python3
import json
# 读取视觉设计项目案例数据
with open('网页未导入数据/视觉设计产业/视觉设计项目案例.json', 'r', encoding='utf-8') as f:
projects_data = json.load(f)
# 读取mock文件
with open('src/mocks/projectLibraryMock.js', 'r', encoding='utf-8') as f:
content = f.read()
# 为每个项目提取附件信息
for idx, project in enumerate(projects_data, 1):
case_name = project.get("案例名称", "")
attachments_str = project.get("附件", "")
if attachments_str:
# 将附件字符串分割成列表
attachments = attachments_str.split(',')
# 创建附件对象列表
attachments_list = []
for attachment in attachments:
attachment = attachment.strip()
# 根据文件扩展名判断类型
ext = attachment.split('.')[-1].lower()
file_type = 'document'
if ext in ['jpg', 'jpeg', 'png', 'gif']:
file_type = 'image'
elif ext in ['mp4', 'avi', 'mov']:
file_type = 'video'
elif ext in ['pdf']:
file_type = 'pdf'
elif ext in ['psd']:
file_type = 'design'
elif ext in ['doc', 'docx']:
file_type = 'word'
attachments_list.append({
'name': attachment,
'type': file_type,
'url': f'/attachments/{attachment}' # 模拟URL
})
# 在projects数组中找到对应的项目并添加attachments字段
search_str = f'"id": {idx},'
idx_pos = content.find(search_str)
if idx_pos != -1:
# 找到项目结束位置下一个id或数组结束
next_id = content.find(f'"id": {idx+1},', idx_pos)
if next_id == -1:
# 最后一个项目找到projects数组结束
end_pos = content.find('];', idx_pos)
else:
end_pos = next_id
# 在项目数据中找到合适的位置插入attachments
# 找到"keyPoints"字段后插入
keypoints_pos = content.rfind('"keyPoints":', idx_pos, end_pos)
if keypoints_pos != -1:
# 找到keyPoints字段的结束位置
line_end = content.find('\n', keypoints_pos)
if line_end != -1 and line_end < end_pos:
# 在keyPoints后面插入attachments字段
insert_pos = line_end
indent = ' '
attachments_str = json.dumps(attachments_list, ensure_ascii=False, indent=8)
# 调整缩进
attachments_str = attachments_str.replace('\n', '\n ')
new_line = f',\n{indent}"attachments": {attachments_str}'
content = content[:insert_pos] + new_line + content[insert_pos:]
# 还需要修改getMockProjectDetail函数
# 查找attachments: []这一行
attachments_line = 'attachments: []'
if attachments_line in content:
content = content.replace(attachments_line, 'attachments: project.attachments || []')
# 写入修改后的内容
with open('src/mocks/projectLibraryMock.js', 'w', encoding='utf-8') as f:
f.write(content)
print("附件数据已添加到mock文件中")