前言
将Typecho文章迁移到Hexo系统,实在是过去太久了,我终于又把我的博客捡起来了,上次写博客还是在5年前,一转眼我就快大学毕业了,想想我之前加入的十年之约博客项目真的是笑话,确实坚持续费服务器的花费是不小的,但是随着年龄的增长和知识储备的增加,应该会使这个博客应该能活到10年吧。
废话说完,这篇文章是讲我如何将typecho的博客系统迁移到hexo的,其实很简单就一个python文件就搞定了,但是评论系统的更换导致原来的记录很难被迁移,所以只能有所取舍,目前我只迁移了所有的文章,并且将tag对应上,至于图片我一开始就用的是对象存储所以问题应该不大。
代码如下
迁移代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
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 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()
|
这个代码也不是全是我原创的,我从网上翻出来然后改了改适应了下我自己的情况,如果需要进一步的迁移你也可以自己修改代码。
结语
总算是回来了,从年轻时候花里胡哨的主题页面,到如今追求访问性能和主题简洁真的是变化不小啊