通过Python调用API接口上传文档到博客园

通过Python调用API接口上传文档到博客园

个人服务器到期,不想续费了,迁移mindoc文档到博客园中

环境

python 3.10

API接口代码

import xmlrpc.client as xmlrpclib
import re
import ssl
import time
import datetime
# import pymysql
import os

ssl._create_default_https_context = ssl._create_unverified_context


# 博客园相关配置接口
class MetablogClient(object):
    def __init__(self):
        # @configpath: 指定配置文件路径
        self._configpath = None
        self._config = {'blogid': "xxxx",
                        "usr": "xxxx",
                        "appkey": "megshuai",
                        "passwd": "xxxxx",
                        "url": "https://rpc.cnblogs.com/xxxx"}
        self._server = xmlrpclib.ServerProxy(self._config["url"])
        self._mwb = self._server.metaWeblog

    def runtest(self):
        cfg = {"url": "https://rpc.cnblogs.com/xxxxx",
               "appkey": "xxxx",
               "usr": "xxxx",
               "passwd": "609B628869BB1DxxxxxxxxxD509F0BADAB5F6E63FFCF7D9"}

    def createConfig(self):
        pass

    def getCategories(self):
        '''
        获取博文分类
        '''

        return self._mwb.getCategories(self._config['blogid'], self._config['usr'], self._config['passwd'])

    def getRecentPosts(self):
        '''
        读取最近的博文信息
        '''
        return self._mwb.getRecentPosts(self._config["blogid"], self._config["usr"], self._config["passwd"], 10)

    def newMediaObject(self, file):
        '''
        资源文件(图片,音频,视频...)上传
        @file: {
          base64	bits
          string	name
          string	type
        }
        @return: URL
        '''
        return self._mwb.newMediaObject(self._config['blogid'], self._config['usr'], self._config['passwd'], file)

    def newPost(self, post, publish):
        '''
        发布新博文
        @post: 发布内容
        @publish: 是否公开
        '''
        while True:
            try:
                print("创建者...")
                postid = self._mwb.newPost(self._config['blogid'], self._config['usr'], self._config['passwd'], post,
                                           publish)
                break
            except:
                time.sleep(5)
                print('123...')
        return postid


class Mindoc(object):
    def __init__(self):
        # 数据库配置信息
        self.config = {
            'user': 'lgs',
            'password': 'meg@314159',
            'host': '47.120.38.203',
            'database': 'mindoc_db'
        }

    def book(self, name):
        # 获取项目id
        conn = pymysql.connect(**self.config)
        # 执行sql 获取对应分类下文章名称
        sql = "select book_id from md_books where book_name='{}';".format(name)
        cursor = conn.cursor()
        cursor.execute(sql)  # 执行SQL语句
        # 读取数据
        title = cursor.fetchall()
        # 关闭游标和连接
        cursor.close()
        conn.close()
        return title[0][0]

    def md_title(self, id):
        title = []
        # 链接数据库
        conn = pymysql.connect(**self.config)
        # 执行sql 获取对应分类下文章名称
        sql = "select document_name from md_documents where book_id={};".format(id)
        cursor = conn.cursor()
        cursor.execute(sql)  # 执行SQL语句
        # 读取数据
        for column2 in cursor:
            title.append(column2[0])
        # 关闭游标和连接
        cursor.close()
        conn.close()
        return title

    def md_article(self, id, title):
        # 链接数据库
        conn = pymysql.connect(**self.config)
        cursor = conn.cursor()
        sql = "select  markdown from md_documents where book_id={} and document_name='{}';".format(id, title)
        cursor.execute(sql)  # 执行SQL语句
        # 读取数据
        article = cursor.fetchall()[0][0]
        # 关闭游标和连接
        cursor.close()
        conn.close()
        return article


class Three(object):
    #图片处理
    def picture(self, article):
        #判断文章是否是否包含文本
        art = re.findall("!\[\]\(/uploads.*\)", article)
        if art != []:
            #获取图片地址 返回列表
            print(art)
            #上传图片
            #替换文章中地址
        else:
            print("文章中不包含图片...")

    # 发布博文
    def runtest(self):
        client = MetablogClient()
        mindoc = Mindoc()
        title = mindoc.md_title()
        for i in title:
            # 获取文章内容
            print(i)
            article = mindoc.md_article(i)
            postid = client.newPost({
                "time": datetime.datetime.now(),
                "title": i,
                "description": article,
                "categories": ["java"]
            }, True)
            print('发布随笔:', postid)
            time.sleep(10)


# if __name__ == "__main__":
#     run = Three()
#     run.runtest()


client = MetablogClient()


def Picture():
    # 上传图片
    picture = {}
    directory = "./markdown/uploads/python/images/"
    filenames = os.listdir(directory)
    for i in filenames:
        filepic = directory + i
        print(filepic)
        with open(filepic, 'rb') as fs:
            bs64_str = fs.read()
            print(bs64_str)
            url = client.newMediaObject({
                "bits": bs64_str,
                "name": str(i),
                "type": "image/png"
            })
            print(url)
            picture[i] = url

    print(picture)

Picture()
```
posted @ 2024-11-12 15:41  帅帅啊  阅读(99)  评论(0)    收藏  举报