开发喵星球

python将md文件发送到wordpress

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
<h1>WordPress的XML-RPC地址,用户名和密码</h1>
wp_url = "https://kaifamiao.dev/xmlrpc.php"
wp_username = "用户名和密码"
wp_password = "用户名和密码"
import collections.abc

collections.Iterable = collections.abc.Iterable
<h1>初始化WordPress客户端</h1>
wp = Client(wp_url, wp_username, wp_password)
<h1>读取目录下所有.md文件</h1>
for md_file in glob.glob("E:\pythonProject\push-md-wordpress\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}.")
</code></pre>
   
分类:Python, 未分类 作者:开发喵 发表于:2023-09-03 22:33:27 阅读量:115
<<   >>


powered by kaifamiao