开发喵星球

Mac下python将md文件发送到wordpress

安装库文件

pip3 install python-wordpress-xmlrpc

pip3 install markdown

import glob, os
import markdown
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost, GetPosts, EditPost
from collections.abc import Iterable
import datetime
import collections.abc
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

# <h1>WordPress的XML-RPC地址,用户名和密码</h1>
wp_url = 'https://kaifamiao.dev/xmlrpc.php'
wp_username = '用户名'
wp_password = '密码'

# <h1>初始化WordPress客户端</h1>
wp = Client("https://kaifamiao.dev/xmlrpc.php", wp_username, wp_password)
# # <h1>读取目录下所有.md文件</h1>
print("start..")
for md_file in glob.glob("./md/*.md"):
    post_title = md_file.split('/')[-1].replace('.md', '')
    post_title = os.path.basename(md_file).replace('.md', '')
    # <pre><code># # 获取文件的创建时间
    # file_ctime = os.path.getctime(md_file)
    # file_date = datetime.datetime.fromtimestamp(file_ctime)

    # 获取文件的最后修改时间
    file_mtime = os.path.getmtime(md_file)
    file_date = datetime.datetime.fromtimestamp(file_mtime)

    print(post_title, file_date)
    # 获取所有文章(这里只获取前50篇文章,你可以根据需要进行调整)
    existing_posts = wp.call(GetPosts({'number': 50}))

    # 在获取的文章中搜索具有相同标题的文章
    existing_post = None
    for post in existing_posts:
        if post.title == post_title:
            existing_post = post
            break

    if existing_post:
        # overwrite = input(f"A post with the title '{post_title}' already exists. Overwrite? (y/n): ")
        overwrite = 'y'  # input(f"A post with the title '{post_title}' already exists. Overwrite? (y/n): ")
        # if overwrite.lower() != 'y':
        #     continue

    with open(md_file, 'r', encoding='utf-8') as f:
        md_content = f.read()

    # 将Markdown转换为HTML
    html_content = markdown.markdown(md_content)
    categories = ['Python']
    tags = ['Python', '开发喵']
    if existing_post:
        # 更新现有文章
        existing_post.content = html_content
        existing_post.terms_names = {
            'category': categories,
            'post_tag': tags
        }
        existing_post.date = file_date

        wp.call(EditPost(existing_post.id, existing_post))
        print(f"Updated post ID {existing_post.id} with new content.")
    else:
        # 创建一个新的WordPress文章
        post = WordPressPost()
        post.title = post_title

        # post.title = os.path.splitext(os.path.basename(md_file))[0]
        post.content = html_content
        post.terms_names = {
            'category': categories,
            'post_tag': tags
        }
        post.date = file_date
        post.post_status = 'publish'  # 文章状态,例如:'draft' 或 'publish'

        # 发布文章
        post_id = wp.call(NewPost(post))
        print(f"Published {md_file} with post ID {post_id}.")

   
分类:Python 作者:开发喵 发表于:2023-09-04 20:47:50 阅读量:134
<<   >>


powered by kaifamiao