Migrating Typecho Posts to Hexo

Translated from the Chinese original. Read the original in 中文

Contents

Preface

Migrating my Typecho posts to Hexo: it has been far too long, but I have finally picked my blog up again. The last time I wrote anything here was five years ago, and in the blink of an eye I am about to graduate from university. Looking back, the "Ten-Year Pact" blog project I joined back then was a bit of a joke — keeping a server paid for year after year is not cheap. Still, now that I am older and know more, this blog should be able to make it to ten years.

Enough rambling. This post is about how I moved my blog from Typecho to Hexo. It is actually simple — a single Python file does the job — but switching comment systems makes the old comments hard to carry over, so I had to make trade-offs. For now I have migrated all the posts and mapped their tags; as for images, I used object storage from the start, so they should be fine.

Here is the code:

Migration code

python
# -*- coding: utf-8 -*-

import os
import pymysql
import arrow
from box import Box


def create_data(db):
    cursor = db.cursor()
    # 创建文章
    cursor.execute("select cid, title, slug, text, created, modified from ty_contents where type='post'")
    # 创建分类和标签
    entries = cursor.fetchall()
    for e in entries:
        e = Box(e)
        title = e.title
        title = title.strip(' ')
        print(title)
        content = str(e.text).replace('<!--markdown-->', '')
        # 文章太长截断
        max_length = 150  # Set the maximum content length here
        if len(content) > max_length:
            content = content[:max_length] + "\n<!--more-->\n" + content[max_length:]
        tags = []

        cursor.execute("select type, name, slug from `ty_relationships` ts, ty_metas tm where tm.mid = ts.mid and ts.cid = %d" % e.cid)
        metas = cursor.fetchall()

        for m in metas:
            m = Box(m)
            if m.type == 'tag':
                tags.append(m.name)
        path = 'data/_posts/'
        if not os.path.exists(path):
            os.makedirs(path)
        filename = arrow.get(e.created).format('YYYY-MM-DD') + " " + title.replace('/', '-')
        f = open(f"{path}/{filename}.md", 'w', encoding="utf-8")
        f.write("---\n")
        f.write("title: '%s'\n" % title)
        f.write("date: %s\n" % arrow.get(e.created).format('YYYY-MM-DD HH:mm:ss'))
        f.write("updated: %s\n" % arrow.get(e.modified).format('YYYY-MM-DD HH:mm:ss'))
        f.write("tags: [%s]\n" % ','.join(tags))
        f.write("published: true\n")
        f.write("lang: zh-cn\n")
        f.write("---\n")
        f.write(content)
        f.close()


def main():
    # 把数据库连接信息

    db = pymysql.connect(host='localhost',
                                 user='root',
                                 password='xxxxx',
                                 database='typecho',
                                 cursorclass=pymysql.cursors.DictCursor)

    create_data(db)


if __name__ == "__main__":
    main()

Not all of this code is my own: I found it online and adapted it to my setup. If you need to migrate more, feel free to modify it yourself.

Closing thoughts

I am finally back. From the flashy themes of my younger days to chasing page speed and a clean design today — quite a change.

Comments