# !/usr/bin python3
# encoding : utf-8 -*-
# @author : coonote
# @software : pycharm
# @file : wordpress.py
# @time : 2021/1/8 10:19 下午
from threading import thread
from queue import queue
from pymongo import mongoclient,collection
import requests
import time
class wordpress_post(thread):
def __init__(self, queue, config):
super(wordpress_post,self).__init__()
self.queue = queue
self.config = config
def run(self) -> none:
while true:
try:
title, content = self.queue.get()
form = self.make_form(title, content)
rts = self.post_article(form)
print(f'{title} {rts}')
finally:
self.queue.task_done()
def post_article(self, form):
try:
r = requests.post(self.config['api'], data=form, timeout=10)
except requests.timeout:
return self.post_article(form)
r.encoding = 'utf-8'
print(r.text)
def make_form(self, title, content):
return {
'post_title':title, # 标题
'post_content':content, # 内容
'tag':'', # 标签
'post_category':'', # 分类
'post_data':'', # 时间
'post_excerpt':'', # 摘要
'post_author':'junge', # 作者
'category_description':'', # 分类信息
'post_cate_meta[name]':'', # 自定义分类信息
'post_meta[name]':'', # 自定义字段
'post_type':'post', # 文章类型 默认为'post'
'post_taxonomy':'', # 自定义分类方式
'post_format':'', # 文章形式
}
# read_article_from_db函数遍历读取mongodb里面数据title,content
def read_article_from_db(collect: collection.collection, from_, num, queue: queue):
# 查找全部数据title,content
result = collect.find({}, {'_id': 0, 'title': 1, 'content': 1}, skip=from_, limit=num)
# 遍历出result里面的数据
for item in result:
# put到消息列队里面
queue.put((item['title'], item['content']))
if __name__ == '__main__':
article_queue = queue(100)
client = mongoclient()
db = client['shuju']
table = db['article']
rdb = thread(target=read_article_from_db, args=(table, 1000, 100, article_queue))
# 守护线程true
rdb.daemon = true
# 启动线程
rdb.start()
# 延时一秒
time.sleep(1)
post_config = {
'api':'这里写接口地址',
'id':1
}
api = '这里写接口地址'
for _ in range(10):
wp = wordpress_post(article_queue,post_config)
wp.daemon = true
wp.start()
article_queue.join()
print('发布完成')