完成wordpress到django站点的数据迁移,下一届阶段完成前端样式的轻度编写
This commit is contained in:
+464
@@ -0,0 +1,464 @@
|
||||
"""
|
||||
WordPress → Django 数据迁移脚本
|
||||
|
||||
功能:
|
||||
1. 连接临时 WordPress 数据库(wp_temp)
|
||||
2. 读取分类、标签、文章
|
||||
3. 清洗数据(路径替换、Markdown 处理)
|
||||
4. 通过 Django ORM 写入新数据库(blog_db)
|
||||
|
||||
使用方法:
|
||||
cd blog_project
|
||||
source venv/bin/activate
|
||||
python migrate_wp.py
|
||||
|
||||
前置条件:
|
||||
- .sql 文件已导入 wp_temp 数据库
|
||||
- Django 模型已 migrate
|
||||
- 本脚本必须在 Django 项目目录下运行(需要加载 settings)
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import pymysql
|
||||
|
||||
import datetime
|
||||
from django.utils import timezone
|
||||
|
||||
from pypinyin import lazy_pinyin
|
||||
import re
|
||||
|
||||
# ========== Django 环境初始化 ==========
|
||||
# 把项目根目录加入 Python 路径
|
||||
# 这样下面才能 import django 和 blog 的模型
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
# 设置 Django 配置文件路径
|
||||
# 告诉 Django 用哪个 settings.py
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'blogsite.settings')
|
||||
|
||||
import django
|
||||
django.setup()
|
||||
|
||||
# 现在可以正常 import Django 模型了
|
||||
from blog.models import Post, Category, Tag
|
||||
from django.utils.text import slugify
|
||||
from django.db import transaction
|
||||
|
||||
|
||||
# ========== 配置区 ==========
|
||||
# WordPress 临时数据库连接信息
|
||||
WP_DB_CONFIG = {
|
||||
'host': '127.0.0.1',
|
||||
'user': 'root',
|
||||
'password': 'guoan123', # ← 改成你的 MySQL 密码
|
||||
'database': 'wp_temp',
|
||||
'charset': 'utf8mb4',
|
||||
'cursorclass': pymysql.cursors.DictCursor # 返回字典而不是元组
|
||||
}
|
||||
|
||||
# WordPress 旧域名(用于图片路径替换)
|
||||
OLD_DOMAIN = 'https://xiaoan.xyz' # ← 改成你实际的旧域名
|
||||
# 替换成新路径前缀
|
||||
NEW_MEDIA_PREFIX = '/media/uploads/'
|
||||
|
||||
|
||||
def connect_wp_db():
|
||||
"""
|
||||
连接 WordPress 临时数据库
|
||||
返回连接对象
|
||||
"""
|
||||
print("正在连接 WordPress 临时数据库...")
|
||||
conn = pymysql.connect(**WP_DB_CONFIG)
|
||||
print("✅ 连接成功")
|
||||
return conn
|
||||
|
||||
|
||||
def clean_content(html_content):
|
||||
"""
|
||||
清洗文章内容
|
||||
|
||||
做的事情:
|
||||
1. 替换图片路径(旧域名 → 新路径)
|
||||
2. (后续可扩展)Markdown 转换等
|
||||
|
||||
参数:
|
||||
html_content: 原始文章内容(HTML 或 Markdown)
|
||||
|
||||
返回:
|
||||
清洗后的内容
|
||||
"""
|
||||
if not html_content:
|
||||
return ''
|
||||
|
||||
content = html_content
|
||||
|
||||
# 1. 替换图片路径
|
||||
# WordPress 里的图片路径长这样:
|
||||
# http://旧域名/wp-content/uploads/2023/01/photo.jpg
|
||||
old_pattern = f'{OLD_DOMAIN}/wp-content/uploads/'
|
||||
content = content.replace(old_pattern, NEW_MEDIA_PREFIX)
|
||||
|
||||
# 也可能有带 https 的
|
||||
old_pattern_https = OLD_DOMAIN.replace('http://', 'https://')
|
||||
old_pattern_https += '/wp-content/uploads/'
|
||||
content = content.replace(old_pattern_https, NEW_MEDIA_PREFIX)
|
||||
|
||||
# 也可能有相对路径形式的
|
||||
content = content.replace('/wp-content/uploads/', NEW_MEDIA_PREFIX)
|
||||
|
||||
# 2. (可选)如果你用了 Markdown 编辑器插件
|
||||
# 内容可能是 Markdown 源码而不是 HTML
|
||||
# 这里先原样保留,后面可以在 C++ 或 Python 里做 md → html 转换
|
||||
# 判断依据:如果内容不以 < 开头,大概率就是 Markdown
|
||||
|
||||
return content
|
||||
|
||||
|
||||
def migrate_categories(conn):
|
||||
"""
|
||||
迁移分类
|
||||
|
||||
WordPress 里分类存在三张表里:
|
||||
- wp_terms: 存名称、slug
|
||||
- wp_term_taxonomy: 存类型(category vs post_tag)和描述
|
||||
- wp_term_relationships: 关联文章和 term
|
||||
"""
|
||||
print("\n" + "=" * 50)
|
||||
print("开始迁移分类...")
|
||||
print("=" * 50)
|
||||
|
||||
with conn.cursor() as cursor:
|
||||
# 修复:所有字段都加上表名前缀,避免 ambiguous 错误
|
||||
sql = """
|
||||
SELECT
|
||||
t.term_id,
|
||||
t.name,
|
||||
t.slug,
|
||||
tt.description,
|
||||
tt.parent
|
||||
FROM wp_terms t
|
||||
INNER JOIN wp_term_taxonomy tt ON t.term_id = tt.term_id
|
||||
WHERE tt.taxonomy = 'category'
|
||||
ORDER BY t.term_id
|
||||
"""
|
||||
cursor.execute(sql)
|
||||
rows = cursor.fetchall()
|
||||
|
||||
print(f"找到 {len(rows)} 个分类")
|
||||
|
||||
category_map = {}
|
||||
|
||||
for row in rows:
|
||||
term_id = row['term_id'] # 现在 row 的 key 是 'term_id'(来自 t.term_id)
|
||||
name = row['name']
|
||||
slug = row['slug']
|
||||
description = row['description'] or ''
|
||||
parent_id = row['parent']
|
||||
|
||||
if not slug:
|
||||
slug = slugify(name)
|
||||
|
||||
category, created = Category.objects.get_or_create(
|
||||
slug=slug,
|
||||
defaults={
|
||||
'name': name,
|
||||
'description': description,
|
||||
}
|
||||
)
|
||||
|
||||
if not created:
|
||||
category.name = name
|
||||
category.description = description
|
||||
category.save()
|
||||
|
||||
category_map[term_id] = category
|
||||
|
||||
status = "新建" if created else "更新"
|
||||
print(f" [{status}] 分类: {name} (slug: {slug})")
|
||||
|
||||
# 第二遍:处理父分类关系
|
||||
print("\n处理父分类关系...")
|
||||
with conn.cursor() as cursor:
|
||||
# 修复:这里也要加表名前缀
|
||||
cursor.execute("""
|
||||
SELECT tt.term_id, tt.parent
|
||||
FROM wp_term_taxonomy tt
|
||||
INNER JOIN wp_terms t ON tt.term_id = t.term_id
|
||||
WHERE tt.taxonomy = 'category' AND tt.parent > 0
|
||||
""")
|
||||
parent_rows = cursor.fetchall()
|
||||
|
||||
for row in parent_rows:
|
||||
child_term_id = row['term_id']
|
||||
parent_term_id = row['parent']
|
||||
|
||||
if child_term_id in category_map and parent_term_id in category_map:
|
||||
child_cat = category_map[child_term_id]
|
||||
parent_cat = category_map[parent_term_id]
|
||||
child_cat.parent = parent_cat
|
||||
child_cat.save()
|
||||
|
||||
print(f"✅ 分类迁移完成,共 {len(category_map)} 个")
|
||||
return category_map
|
||||
|
||||
|
||||
def migrate_tags(conn):
|
||||
"""
|
||||
迁移标签
|
||||
"""
|
||||
print("\n" + "=" * 50)
|
||||
print("开始迁移标签...")
|
||||
print("=" * 50)
|
||||
|
||||
with conn.cursor() as cursor:
|
||||
# 修复:加表名前缀
|
||||
sql = """
|
||||
SELECT
|
||||
t.term_id,
|
||||
t.name,
|
||||
t.slug
|
||||
FROM wp_terms t
|
||||
INNER JOIN wp_term_taxonomy tt ON t.term_id = tt.term_id
|
||||
WHERE tt.taxonomy = 'post_tag'
|
||||
ORDER BY t.term_id
|
||||
"""
|
||||
cursor.execute(sql)
|
||||
rows = cursor.fetchall()
|
||||
|
||||
print(f"找到 {len(rows)} 个标签")
|
||||
|
||||
tag_map = {}
|
||||
|
||||
for row in rows:
|
||||
term_id = row['term_id']
|
||||
name = row['name']
|
||||
slug = row['slug']
|
||||
|
||||
if not slug:
|
||||
slug = slugify(name)
|
||||
|
||||
tag, created = Tag.objects.get_or_create(
|
||||
slug=slug,
|
||||
defaults={'name': name}
|
||||
)
|
||||
|
||||
if not created:
|
||||
tag.name = name
|
||||
tag.save()
|
||||
|
||||
tag_map[term_id] = tag
|
||||
|
||||
status = "新建" if created else "更新"
|
||||
print(f" [{status}] 标签: {name}")
|
||||
|
||||
print(f"✅ 标签迁移完成,共 {len(tag_map)} 个")
|
||||
return tag_map
|
||||
|
||||
|
||||
def migrate_posts(conn, category_map, tag_map):
|
||||
"""
|
||||
迁移文章(含分类标签关联)
|
||||
"""
|
||||
print("\n" + "=" * 50)
|
||||
print("开始迁移文章...")
|
||||
print("=" * 50)
|
||||
|
||||
with conn.cursor() as cursor:
|
||||
# 修复:wp_posts 字段加表名前缀
|
||||
sql = """
|
||||
SELECT
|
||||
p.ID,
|
||||
p.post_name,
|
||||
p.post_title,
|
||||
p.post_content,
|
||||
p.post_excerpt,
|
||||
p.post_date,
|
||||
p.post_status
|
||||
FROM wp_posts p
|
||||
WHERE p.post_type = 'post'
|
||||
AND p.post_status IN ('publish', 'draft', 'private')
|
||||
ORDER BY p.post_date DESC
|
||||
"""
|
||||
cursor.execute(sql)
|
||||
rows = cursor.fetchall()
|
||||
|
||||
print(f"找到 {len(rows)} 篇文章")
|
||||
|
||||
# 查询文章和分类/标签的关联
|
||||
with conn.cursor() as cursor:
|
||||
# 修复:所有字段加表名前缀
|
||||
cursor.execute("""
|
||||
SELECT
|
||||
tr.object_id AS post_id,
|
||||
tt.term_id,
|
||||
tt.taxonomy
|
||||
FROM wp_term_relationships tr
|
||||
INNER JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
|
||||
WHERE tt.taxonomy IN ('category', 'post_tag')
|
||||
""")
|
||||
rel_rows = cursor.fetchall()
|
||||
|
||||
# 整理关联关系
|
||||
post_relations = {}
|
||||
for rel in rel_rows:
|
||||
pid = rel['post_id']
|
||||
tid = rel['term_id']
|
||||
tax = rel['taxonomy']
|
||||
|
||||
if pid not in post_relations:
|
||||
post_relations[pid] = {'category': [], 'post_tag': []}
|
||||
if tax in ('category', 'post_tag'):
|
||||
post_relations[pid][tax].append(tid)
|
||||
|
||||
# 逐篇迁移(后面的逻辑不变)
|
||||
success_count = 0
|
||||
skip_count = 0
|
||||
|
||||
for row in rows:
|
||||
post_id = row['ID']
|
||||
title = row['post_title']
|
||||
slug = row['post_name'] or ''
|
||||
if not slug:
|
||||
slug = f'post-{post_id}'
|
||||
|
||||
# 如果 slug 里有 % 说明被 URL 编码了,先解码
|
||||
if '%' in slug:
|
||||
from urllib.parse import unquote
|
||||
slug = unquote(slug)
|
||||
|
||||
# 如果 slug 包含非 ASCII 字符(中文等),转拼音
|
||||
if not re.match(r'^[a-zA-Z0-9_-]+$', slug):
|
||||
# 用 pypinyin 转成拼音列表,再用 - 连接
|
||||
pinyin_list = lazy_pinyin(slug, style=0) # style=0 是普通风格
|
||||
slug = '-'.join(pinyin_list)
|
||||
# 清理掉多余的符号
|
||||
slug = re.sub(r'[^a-zA-Z0-9-]', '', slug).strip('-')
|
||||
# 如果转完是空的(极端情况),用 ID 兜底
|
||||
if not slug:
|
||||
slug = f'post-{post_id}'
|
||||
|
||||
content = row['post_content'] or ''
|
||||
excerpt = row['post_excerpt'] or ''
|
||||
post_date_raw = row['post_date']
|
||||
if isinstance(post_date_raw, str):
|
||||
# 如果是字符串,先解析成 datetime 对象
|
||||
post_date = datetime.datetime.strptime(post_date_raw, '%Y-%m-%d %H:%M:%S')
|
||||
# 标记为上海时区(WordPress 里存的时间通常是服务器本地时间)
|
||||
post_date = timezone.make_aware(post_date, timezone=timezone.get_fixed_timezone(480)) # UTC+8 = 480分钟
|
||||
elif isinstance(post_date_raw, datetime.datetime):
|
||||
if timezone.is_naive(post_date_raw):
|
||||
# 已经是 datetime 但不带时区,加上 UTC+8
|
||||
post_date = timezone.make_aware(post_date_raw, timezone=timezone.get_fixed_timezone(480))
|
||||
else:
|
||||
post_date = post_date_raw
|
||||
else:
|
||||
# 兜底:用当前时间
|
||||
post_date = timezone.now()
|
||||
post_status = row['post_status']
|
||||
|
||||
if not slug:
|
||||
slug = f'post-{post_id}'
|
||||
|
||||
status_map = {
|
||||
'publish': 'published',
|
||||
'draft': 'draft',
|
||||
'private': 'draft',
|
||||
}
|
||||
status = status_map.get(post_status, 'draft')
|
||||
|
||||
cleaned_content = clean_content(content)
|
||||
cleaned_excerpt = clean_content(excerpt)
|
||||
|
||||
try:
|
||||
with transaction.atomic():
|
||||
post, created = Post.objects.get_or_create(
|
||||
slug=slug,
|
||||
defaults={
|
||||
'title': title,
|
||||
'content': cleaned_content,
|
||||
'excerpt': cleaned_excerpt,
|
||||
'published_at': post_date,
|
||||
'status': status,
|
||||
}
|
||||
)
|
||||
|
||||
if not created:
|
||||
post.title = title
|
||||
post.content = cleaned_content
|
||||
post.excerpt = cleaned_excerpt
|
||||
post.published_at = post_date
|
||||
post.status = status
|
||||
post.save()
|
||||
|
||||
if post_id in post_relations:
|
||||
rels = post_relations[post_id]
|
||||
|
||||
post.categories.clear()
|
||||
for tid in rels.get('category', []):
|
||||
if tid in category_map:
|
||||
post.categories.add(category_map[tid])
|
||||
|
||||
post.tags.clear()
|
||||
for tid in rels.get('post_tag', []):
|
||||
if tid in tag_map:
|
||||
post.tags.add(tag_map[tid])
|
||||
|
||||
success_count += 1
|
||||
action = "新建" if created else "更新"
|
||||
print(f" [{action}] 文章: {title} (slug: {slug})")
|
||||
|
||||
except Exception as e:
|
||||
skip_count += 1
|
||||
print(f" ❌ 失败: {title} - {str(e)}")
|
||||
|
||||
print(f"\n✅ 文章迁移完成: 成功 {success_count} 篇, 跳过 {skip_count} 篇")
|
||||
|
||||
|
||||
def main():
|
||||
"""
|
||||
主函数
|
||||
按顺序执行迁移步骤
|
||||
"""
|
||||
print("""
|
||||
╔══════════════════════════════════════╗
|
||||
║ WordPress → Django 数据迁移工具 ║
|
||||
╚══════════════════════════════════════╝
|
||||
""")
|
||||
|
||||
# 1. 连接数据库
|
||||
conn = connect_wp_db()
|
||||
|
||||
try:
|
||||
# 2. 迁移分类
|
||||
category_map = migrate_categories(conn)
|
||||
|
||||
# 3. 迁移标签
|
||||
tag_map = migrate_tags(conn)
|
||||
|
||||
# 4. 迁移文章(含分类标签关联)
|
||||
migrate_posts(conn, category_map, tag_map)
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("🎉 全部迁移完成!")
|
||||
print("=" * 50)
|
||||
print("\n接下来你可以:")
|
||||
print(" 1. 启动 runserver 查看文章列表")
|
||||
print(" 2. 确认分类和标签是否正确关联")
|
||||
print(" 3. 开始处理图片迁移(wp-content/uploads → media/uploads)")
|
||||
print(" 4. 引入 C++ 图片处理工具")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n❌ 迁移过程中出错: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
finally:
|
||||
# 关闭数据库连接
|
||||
conn.close()
|
||||
print("\n数据库连接已关闭")
|
||||
|
||||
|
||||
# 脚本入口
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user