使用Python将Halo文章导出为Hexo格式的md文件

2022-03-16 10:55:03
import pymysql

db = pymysql.connect("192.168.11.12", "root", "123", "halodb")


def create_file(file_path, msg):
    f = open(file_path, "a")
    f.write(msg)
    
    f.close


def get_categories(post_id):
    cursor = db.cursor()
    sql = 'select name from categories where id in(select category_id from post_categories where post_id={})'.format(
        post_id)
    cursor.execute(sql)
    categories = cursor.fetchall()
    if len(categories) == 0: return ''
    if len(categories) > 1:
        category_str = '[{}]'.format(','.join([category[0] for category in categories]))
    else:
        category_str = categories[0][0]

    return category_str


def get_tags(post_id):
    cursor = db.cursor()
    sql = 'select name from tags where id in (select tag_id from post_tags where post_id={})'.format(
        post_id)
    cursor.execute(sql)
    tags = cursor.fetchall()
    if len(tags) == 0: return ''
    if len(tags) > 1:
        tag_str = '[{}]'.format(','.join([tag[0] for tag in tags]))
    else:
        tag_str = tags[0][0]
    return tag_str


def mkdir(path):
    # 引入模块
    import os

    # 去除首位空格
    path = path.strip()
    # 去除尾部 \ 符号
    path = path.rstrip("\\")

    # 判断路径是否存在
    # 存在     True
    # 不存在   False
    isExists = os.path.exists(path)

    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        os.makedirs(path)

        print
        path + ' 创建成功'
        return True
    else:
        # 如果目录存在则不创建,并提示目录已存在
        print
        path + ' 目录已存在'
        return False


cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
# SQL 查询语句
sql = "SELECT id,title,original_content,create_time FROM posts where id>115"
content_prefix = '''\
---
author: zze
title: {title}
date: {create_time}
tags: {tags}
categories: {categories}
---
'''
try:
    # 执行SQL语句
    cursor.execute(sql)
    while 1:
        one = cursor.fetchone()
        if one:
            id = one.get('id')
            title = one.get('title')
            content = one.get('original_content')
            create_time = one.get('create_time')
            categories = get_categories(id)
            tags = get_tags(id)
            current_prefix = content_prefix.format(title=title, create_time=create_time, tags=tags,
                                                   categories=categories)
            filepath = 'blogs/{}/{}.md'.format(categories, title.replace('/','&'))
            print('category:{},id:{},filepath:{}'.format(categories, id, filepath))
            mkdir('blogs/{}'.format(categories))
            content = '{}\n{}'.format(current_prefix, content)
            content = content.replace('```HTML', '```html').replace('```XML', '```xml') \
                .replace('```JAVA', '```java').replace('```C#', '```c#') \
                .replace('```JSON', '```json').replace('```SHELL', '```shell') \
                .replace('```BASH', '```bash').replace('```PY', '```py')
            create_file(filepath, content)
        else:
            break
except:
    print("Error: unable to fetch data")
# 关闭数据库连接
db.close()