使用metaweblog API实现通用博客发布 之 API测试

使用博客比较少,一则是文笔有限,怕写出的东西狗屁不通,有碍观瞻, 二则是懒,很讨厌要登录到网站上写东西,也没有那么多时间(借口)。个人最喜欢用于记录的工具是Zim https://zim-wiki.org/ ,记录东西超级方便,可惜只支持PC版本, 记录的东西可以到处为MarkDown 格式,非常方便(你现在看到的这篇就是用Zim写的)。

无意间看到Vs Code上有博客园的插件,作为程序员,顺手google/百度了一下,原来通用博客都支持使用metaweblog API来访问,还支持直接发布markdown 格式,简直不要太好。 找了找2年前注册的博客源账号,用来测试一下。

发挥典型中国程序员的拿来主义精神,经过goolgle/百度一番搜索,参考以下文档进行API测试,在此表示感谢!!

https://www.cnblogs.com/caipeiyu/p/5475761.html

https://github.com/1024th/cnblogs_githook

1 在哪里找API说明

在博客设置最的最末端,有MetaWeblog 的访问地址链接

点击进入页面,有metaweblog API 的详细说明

具体内容不赘述了。

2 测试API

使用python3 进行API测试,直接上代码:

	#encoding = utf-8
#!/bin/sh python3 import xmlrpc.client as xmlrpclib
import json '''
配置字典:
type | description(example)
str | metaWeblog url, 博客设置中有('https://rpc.cnblogs.com/metaweblog/1024th')
str | appkey, Blog地址名('1024th')
str | blogid, 这个无需手动输入,通过getUsersBlogs得到
str | usr, 登录用户名
str | passwd, 登录密码
str | rootpath, 博文存放根路径(添加git管理)
''' '''
POST:
dateTime dateCreated - Required when posting.
string description - Required when posting.
string title - Required when posting.
array of string categories (optional)
struct Enclosure enclosure (optional)
string link (optional)
string permalink (optional)
any postid (optional)
struct Source source (optional)
string userid (optional)
any mt_allow_comments (optional)
any mt_allow_pings (optional)
any mt_convert_breaks (optional)
string mt_text_more (optional)
string mt_excerpt (optional)
string mt_keywords (optional)
string wp_slug (optional)
''' class MetablogClient():
def __init__(self, configpath):
'''
@configpath: 指定配置文件路径
'''
self._configpath = configpath
self._config = None
self._server = None
self._mwb = None def createConfig(self):
'''
创建配置
'''
while True:
cfg = {}
for item in [("url", "metaWeblog url, 博客设置中有\
('https://rpc.cnblogs.com/metaweblog/blogaddress')"),
("appkey", "Blog地址名('blogaddress')"),
("usr", "登录用户名"),
("passwd", "登录密码"),
("rootpath", "博文本地存储根路径")]:
cfg[item[0]] = input("输入"+item[1])
try:
server = xmlrpclib.ServerProxy(cfg["url"])
userInfo = server.blogger.getUsersBlogs(
cfg["appkey"], cfg["usr"], cfg["passwd"])
print(userInfo[0])
# {'blogid': 'xxx', 'url': 'xxx', 'blogName': 'xxx'}
cfg["blogid"] = userInfo[0]["blogid"]
break
except:
print("发生错误!")
with open(self._configpath, "w", encoding="utf-8") as f:
json.dump(cfg, f, indent=4, ensure_ascii=False) def existConfig(self):
'''
返回配置是否存在
'''
try:
with open(self._configpath, "r", encoding="utf-8") as f:
try:
cfg = json.load(f)
if cfg == {}:
return False
else:
return True
except json.decoder.JSONDecodeError: # 文件为空
return False
except:
with open(self._configpath, "w", encoding="utf-8") as f:
json.dump({}, f)
return False def readConfig(self):
'''
读取配置
'''
if not self.existConfig():
self.createConfig() with open(self._configpath, "r", encoding="utf-8") as f:
self._config = json.load(f)
self._server = xmlrpclib.ServerProxy(self._config["url"])
self._mwb = self._server.metaWeblog def getUsersBlogs(self):
'''
获取博客信息
@return: {
string blogid
string url
string blogName
}
'''
userInfo = self._server.blogger.getUsersBlogs(self._config["appkey"], self._config["usr"], self._config["passwd"])
return userInfo def getRecentPosts(self, num):
'''
读取最近的博文信息
'''
return self._mwb.getRecentPosts(self._config["blogid"], self._config["usr"], self._config["passwd"], num) def newPost(self, post, publish):
'''
发布新博文
@post: 发布内容
@publish: 是否公开
'''
while True:
try:
postid = self._mwb.newPost(self._config['blogid'], self._config['usr'], self._config['passwd'], post, publish)
break
except:
time.sleep(5)
return postid def editPost(self, postid, post, publish):
'''
更新已存在的博文
@postid: 已存在博文ID
@post: 发布内容
@publish: 是否公开发布
'''
self._mwb.editPost(postid, self._config['usr'], self._config['passwd'], post, publish) def deletePost(self, postid, publish):
'''
删除博文
'''
self._mwb.deletePost(self._config['appkey'], postid, self._config['usr'], self._config['passwd'], post, publish) def getCategories(self):
'''
获取博文分类
'''
return self._mwb.getCategories(self._config['blogid'], self._config['usr'], self._config['passwd']) def getPost(self, postid):
'''
读取博文信息
@postid: 博文ID
@return: POST
'''
return self._mwb.getPost(postid, self._config['usr'], self._config['passwd']) 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 newCategory(self, categoray):
'''
新建分类
@categoray: {
string name
string slug (optional)
integer parent_id
string description (optional)
}
@return : categorayid
'''
return self._server.wp.newCategory(self._config['blogid'], self._config['usr'], self._config['passwd'], categoray)
``` 以上是对API的简单封装,万事具备,开始测试 ### 2.1 获取分类
```python
import core.metablogclient as blogclient client = blogclient.MetablogClient('blog_config.json')
client.readConfig()
catLst = client.getCategories()
print(catLst)
	[{'description': '[发布至博客园首页]', 'htmlUrl': '', 'rssUrl': '', 'title': '[发布至博客园首页]', 'categoryid': '0'},
{'description': '[Markdown]', 'htmlUrl': '', 'rssUrl': '', 'title': '[Markdown]', 'categoryid': '-5'}...]

获取了所有的分类信息,其中我在网站上自建了一个随笔分类,也可以获取到

2.2 新建分类

	import core.metablogclient as blogclient

	client = blogclient.MetablogClient('blog_config.json')
client.readConfig()
catid = client.newCategory({
"name": "[随笔分类]测试分类",
"slug": "",
"parent_id": 0,
"description": "测试建立一个随笔子分类"
})
print("新建分类:", catid)
	新建分类: 1536823

但是在博客园网站上无法看到这个分类,使用获取分类再次测试,也无法获取到该分类,使用该分类发布博客,也是无

效的,所以我想__根据年月自动分类__的想法就泡汤啦

2.3 拉取现有博文

	import core.metablogclient as blogclient

	client = blogclient.MetablogClient('blog_config.json')
client.readConfig()
posts = client.getRecentPosts(9999)
print(posts)
	[{'dateCreated': <DateTime '20190829T11:21:00' at 0x2a80990>, 'description': '<p>测试</p>', 'title': '测试', 'enclosure': {'length': 0},
'link': 'https://www.cnblogs.com/robert-9/p/11428668.html', 'permalink': 'https://www.cnblogs.com/robert-9/p/11428668.html',
'postid': '11428668', 'source': {}, 'userid': '-2'}]

正确拉取现有博文,通过API文档,发现无法获取博文是否处于发布状态,这是一个遗憾

2.4 发布博文

	import core.metablogclient as blogclient
import datetime client = blogclient.MetablogClient('blog_config.json')
client.readConfig()
postid = client.newPost({
"time": datetime.datetime.now(),
"title": "metaweblog API随笔发布",
"description": "##metaweblog API随笔发布\n测试\n",
"categories": ["[Markdown]"],
"mt_keywords": "metaweblog;python"
}, False)
print('发布随笔:', postid)

测试发布成功,并能在网站上看到该随笔, 如果想发布为文章,日志或新闻,加入必要的分类即可。

2.5 上传图片

	import datetime
import base64
import core.metablogclient as blogclient client = blogclient.MetablogClient('blog_config.json')
client.readConfig()
with open('abc.png', 'rb') as f:
bs64_str = base64.b64encode(f.read())
url = client.newMediaObject({
"bits": bs64_str,
"name": "abc.png",
"type": "image/png"
})
print(url)
	{'url': 'https://img2018.cnblogs.com/blog/1211514/201908/1211514-20190829114435333-814710358.png'}

测试成功, 这样就可以在上传Markdown 格式之前,自动将本地的图片上传到服务器上了。

使用metaweblog API实现通用博客发布 之 API测试的更多相关文章

  1. 使用metaweblog API实现通用博客发布 之 版本控制

    使用metaweblog API实现通用博客发布 之 版本控制 接上一篇本地图片自动上传以及替换路径,继续解决使用API发布博客的版本控制问题. 当本地文档修订更新以后,如何发现版本更新,并自动发布到 ...

  2. 使用metaweblog API实现通用博客发布 之 本地图片自动上传以及替换路径

    使用metaweblog API实现通用博客发布 之 本地图片自动上传以及替换路径 通过metaweblog API 发布博文的时候,由于markdown中的图片路径是本地路径,将导致发布的文章图片不 ...

  3. 使用Office-Word的博客发布功能(测试博文)

    本人打算在博客园开博,但平时收集和整理资料都在OneNote中,又不想在写博客时还要进行复制粘贴操作,于是就想到了Microsoft Office自带的博客发布功能.在此做了一下测试,发布了此博文. ...

  4. 汇总博客常见的api接口地址(windows live write)

    汇总博客常见的api接口地址(windows live write) 1. cnblogs 日志地址,直接输入 http://www.cnblogs.com/xxxxx/ api接口 http://w ...

  5. 【转】如何使用离线博客发布工具发布CSDN的博客文章

    目前大部分的博客作者在用Word写博客这件事情上都会遇到以下3个痛点: 1.所有博客平台关闭了文档发布接口,用户无法使用Word,Windows Live Writer等工具来发布博客.使用Word写 ...

  6. BlogPublishTool - 博客发布工具

    BlogPublishTool - 博客发布工具 这是一个发布博客的工具.本博客使用本工具发布. 本工具源码已上传至github:https://github.com/ChildishChange/B ...

  7. 修改vscode caipeiyu.writeCnblog ,简化博客发布

    修改vscode caipeiyu.writeCnblog ,简化博客发布 1. 安装caipeiyu.writeCnblog vscode的博客园文章发布插件WriteCnblog : https: ...

  8. longblogV1.0——我的静态博客发布系统

    longblogV1.0——我的静态博客发布系统 环境依赖: python3-markdown 作者:IT小小龙个人主页:http://long_python.gitcafe.com/电子邮箱:lon ...

  9. Mac端博客发布工具推荐

    引子 推荐一款好用的 Mac 端博客发布工具. 下载地址 echo 博客对接 这里以cnblog为例.接入类型为metawebblog,access point可以在cnblog的设置最下边找到,然后 ...

随机推荐

  1. 常见的嵌入式linux学习和如何选择ARM芯片问答

    常见的ARM嵌入式学习问答,设计者和学习者最关心的11个问题: 1.          ARM嵌入式是学习硬件好还是学习软件好? 2.          嵌入式软件和硬件,哪一种职位待遇更高?或者说, ...

  2. Notes about WindowPadX

    WindowPadX乃一Autohotkey脚本,具有强大的单/多显示器窗口排布能力且易于配置.有了它,那些Pro版收费的.需要安装的DisplayFusion, MultiMon TaskBar, ...

  3. kubernetes中headless类型的service

    目录 初识headless类型的service 开始研究headless类型的service headless类型的service之我的理解 初识headless类型的service 第一次使用ran ...

  4. S3C2440—9.复制程序到SDRAM中执行

    文章目录 一.S3C2440的启动方式 二.代码 一.S3C2440的启动方式 S3C2440的MMU有一种"steppingstone".技术,是协助MCU从无法执行程序的NAN ...

  5. STM32—SPI详解

    目录 一.什么是SPI 二.SPI协议 物理层 协议层 1.通讯时序图 2.起始和停止信号 3.数据有效性 4.通讯模式 三.STM32中的SPI 简介 功能框图 1.通讯引脚 2.时钟控制逻辑 3. ...

  6. 题解 Defence

    传送门 发现最少次数只和最左,最右及中间最长的全0段有关 本来想启发式合并,结果发现直接线段树合并搭配一个类似山海经的方法就可以过了 yysy,线段树单次合并的具体复杂度并不是 \(O(logn)\) ...

  7. vs code 调试angular2

    调试步骤: 1.安装nodejs 2.安装vscode 3.vscode安装debugger for chrome插件 4.选择调试->打开调试配置,选择chrome配置,打开lauch.jso ...

  8. C#基础知识---?为何物

    一. 可空类型修饰符(?)引用类型可以使用空引用表示一个不存在的值,而值类型通常不能表示为空.例如:string str=null; 是正确的,int i=null; 编译器就会报错.可空类型的出现, ...

  9. 【转】new和malloc的区别

    1. 申请的内存所在位置 new操作符从自由存储区(free store)上为对象动态分配内存空间,而malloc函数从堆上动态分配内存. 自由存储区是C++基于new操作符的一个抽象概念,凡是通过n ...

  10. C++ template模板编程

    模板是C++泛型编程的基础,一个模板就是一个创建类或者函数的蓝图或者公式.当使用一个vector这样的泛型类型,我们提供足够的信息,就可以将蓝图转换成特定的类或者函数. 假设我们编写一个函数来比较两个 ...