125 lines
4.4 KiB
Python
125 lines
4.4 KiB
Python
import os
|
|
import random
|
|
import sys
|
|
import tempfile
|
|
|
|
import django
|
|
|
|
# 配置 Django 环境
|
|
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
|
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") # 修改为你的 settings 路径
|
|
django.setup()
|
|
|
|
# 2. 导入 Faker 和 模型
|
|
|
|
from faker import Faker
|
|
from article.models import Article, ArticleAttachment
|
|
from base.models import MainMenu
|
|
from users.models import User
|
|
from django.core.files import File # 引入 Django 的文件处理类
|
|
|
|
fake = Faker('zh_CN')
|
|
|
|
|
|
def seed_articles(count=20):
|
|
print(f"🚀 开始生成 {count} 篇文章...")
|
|
|
|
subsections = list(MainMenu.objects.filter(parent__isnull=False, visible=True))
|
|
users = list(User.objects.all())
|
|
|
|
if not subsections:
|
|
print("❌ 错误:数据库中没有找到任何子板块!")
|
|
return
|
|
|
|
if not users:
|
|
print("⚠️ 警告:数据库中没有用户,作者将设为空。")
|
|
|
|
created_count = 0
|
|
for i in range(count):
|
|
section = random.choice(subsections)
|
|
author = random.choice(users) if users else None
|
|
|
|
# --- 2. 构建丰富的 HTML 内容 ---
|
|
html_parts = []
|
|
|
|
# A. 开头:一段引言或摘要
|
|
if random.random() > 0.5:
|
|
html_parts.append(f"<p><strong>【摘要】</strong> {fake.sentence(nb_words=10)}</p>")
|
|
|
|
# B. 正文第一段
|
|
html_parts.append(f"<p>{fake.paragraph(nb_sentences=4)}</p>")
|
|
|
|
# C. 随机插入图片占位符 (模拟上传的封面或插图)
|
|
# 使用 placehold.co 生成带文字的灰色占位图
|
|
img_width = random.choice([600, 800])
|
|
img_height = random.choice([300, 400])
|
|
img_text = fake.words(nb=3, unique=True)
|
|
html_parts.append(
|
|
f'<div style="text-align: center; margin: 20px 0;"><img src="https://placehold.co/{img_width}x{img_height}/23418A/FFF?text={"+".join(img_text)}" style="max-width: 100%; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);"></div>')
|
|
|
|
# D. 正文中间段落
|
|
html_parts.append(f"<p>{fake.paragraph(nb_sentences=5)}</p>")
|
|
|
|
# E. 随机插入引用块 (增加排版层次感)
|
|
if random.random() > 0.6:
|
|
quote = fake.sentence(nb_words=8)
|
|
html_parts.append(
|
|
f'<blockquote style="border-left: 5px solid #23418A; padding: 10px 20px; margin: 20px 0; background: #f8f9fa; color: #555;"><i>"{quote}"</i></blockquote>')
|
|
|
|
# F. 随机插入无序列表 (模拟要点陈述)
|
|
if random.random() > 0.7:
|
|
list_items = "".join([f"<li>{fake.sentence()}</li>" for _ in range(3)])
|
|
html_parts.append(f"<ul style='margin: 20px 0; padding-left: 20px;'>{list_items}</ul>")
|
|
|
|
# G. 加粗和斜体混合段落
|
|
p1 = fake.paragraph(nb_sentences=2)
|
|
p2 = fake.paragraph(nb_sentences=2)
|
|
html_parts.append(f"<p>{p1} <strong style='color: #23418A;'>{fake.words(nb=4, unique=True)}</strong> {p2}</p>")
|
|
|
|
# H. 结尾
|
|
html_parts.append(f"<p>{fake.paragraph(nb_sentences=3)}</p>")
|
|
|
|
# 拼接最终 HTML
|
|
content_html = "\n".join(html_parts)
|
|
|
|
article = Article.objects.create(
|
|
title=fake.sentence(nb_words=random.randint(5, 10))[:-1],
|
|
section=section,
|
|
author=author,
|
|
content=content_html,
|
|
is_published=True,
|
|
)
|
|
|
|
# --- 生成真实附件 ---
|
|
if random.random() < 0.3:
|
|
fake_filename = f"附件资料_{fake.word()}.pdf"
|
|
|
|
# 创建临时文件
|
|
with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as tmp_file:
|
|
tmp_file.write(b'%PDF-1.4 Fake PDF Content for Testing')
|
|
tmp_file_path = tmp_file.name
|
|
|
|
try:
|
|
# 打开并保存
|
|
with open(tmp_file_path, 'rb') as f:
|
|
# 关键点:使用 file.save 方法,这会触发文件上传机制
|
|
attachment = ArticleAttachment(article=article)
|
|
attachment.file.save(fake_filename, File(f), save=True)
|
|
|
|
print(f" - [{section}] {article.title} (含真实附件)")
|
|
|
|
finally:
|
|
# 删除临时文件
|
|
if os.path.exists(tmp_file_path):
|
|
os.remove(tmp_file_path)
|
|
else:
|
|
print(f" - [{section}] {article.title}")
|
|
|
|
created_count += 1
|
|
|
|
print(f"✅ 成功生成 {created_count} 篇文章!")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
seed_articles(120)
|