如何在WordPress中使用Python创建帖子?

时间:2019-02-10 作者:Alex R

我在这里找到了API参考:https://v2.wp-api.org/reference/posts/

基于上述API参考,我编写了以下Python代码:

from urllib.request import Request, urlopen
from datetime import datetime

import json

def create(wordpressUrl, content):

    params = {
        \'date_gmt\': datetime.now().replace(microsecond=0).isoformat() + "Z",
        \'status\': \'publish\',
        \'title\': \'The Title\',
        \'author\': \'The Author\',
        \'content\': content
    }
    postparam = json.dumps(params).encode(\'utf-8\')
    req = Request(wordpressUrl + "/wp-json/wp/v2/posts", method=\'POST\', data=postparam)
    req.add_header(\'Content-Type\', \'application/json\')
    r = urlopen(req)

    if(r.getcode() != 200):
        raise Exception("failed with rc=" + r.getcode())

    return json.loads(r.read())
为什么调用此代码时,WP API只返回站点的“关于”页面,而不创建新帖子?我还可以如何在Wordpress内部创建帖子,使用Python调用WP API?

2 个回复
最合适的回答,由SO网友:crifan 整理而成

@prathamesh patil 喂,你错过了authentication = your jwt token

如何生成jwt token ?

  • 简单=核心逻辑安装并启用WordPress插件:JWT Authentication for WP REST APIHTTP:Authorization<用途:允许呼叫/wp-json/jwt-auth/v1 api添加JWT_AUTH_SECRET_KEY 进入wp-config.phpPOST https://www.yourWebsite.com/wp-json/jwt-auth/v1/token 使用wordpressusernamepassword, 响应包含您的预期jwt token<看起来像:eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvd3d3LmNyaWZhbi5jb20iLCJpYXQiOjE1ODQxMDk4OTAsIm5iZiI6MTU4NDEwOTg5MCwiZXhwIjoxNTg0NzE0NjkwLCJkYXRhIjp7InVzZXIiOnsiaWQiOiIxIn19fQ.YvFzitTfIZaCwtkxKTIjP715795OMAVQowgnD8G3wk0Publish WordPress Post with Python Requests and REST API - Stack Overflow

        def createPost(self,
                title,
                content,
                dateStr,
                slug,
                categoryNameList=[],
                tagNameList=[],
                status="draft",
                postFormat="standard"
            ):
            """Create wordpress standard post
                by call REST api: POST /wp-json/wp/v2/posts
    
            Args:
                title (str): post title
                content (str): post content of html
                dateStr (str): date string
                slug (str): post slug url
                categoryNameList (list): category name list
                tagNameList (list): tag name list
                status (str): status, default to \'draft\'
                postFormat (str): post format, default to \'standard\'
            Returns:
                (bool, dict)
                    True, uploaded post info
                    False, error detail
            Raises:
            """
            curHeaders = {
                "Authorization": self.authorization,
                "Content-Type": "application/json",
                "Accept": "application/json",
            }
            logging.debug("curHeaders=%s", curHeaders)
    
            categoryIdList = []
            tagIdList = []
    
            if categoryNameList:
                # [\'Mac\']
                categoryIdList = self.getTaxonomyIdList(categoryNameList, taxonomy="category")
                # category nameList=[\'Mac\'] -> taxonomyIdList=[1374]
    
            if tagNameList:
                # [\'切换\', \'GPU\', \'pmset\', \'显卡模式\']
                tagIdList = self.getTaxonomyIdList(tagNameList, taxonomy="post_tag")
                # post_tag nameList=[\'切换\', \'GPU\', \'pmset\', \'显卡模式\'] -> taxonomyIdList=[1367, 13224, 13225, 13226]
    
            postDict = {
                "title": title, # \'【记录】Mac中用pmset设置GPU显卡切换模式\'
                "content": content, # \'<html>\\n <div>\\n  折腾:\\n </div>\\n <div>\\n  【已解决】Mac Pro 2018款发热量大很烫非常烫\\n </div>\\n <div>\\n  期间,...performance graphic cards\\n    </li>\\n   </ul>\\n  </ul>\\n </ul>\\n <div>\\n  <br/>\\n </div>\\n</html>\'
                # "date_gmt": dateStr,
                "date": dateStr, # \'2020-08-17T10:16:34\'
                "slug": slug, # \'on_mac_pmset_is_used_set_gpu_graphics_card_switching_mode\'
                "status": status, # \'draft\'
                "format": postFormat, # \'standard\'
                "categories": categoryIdList, # [1374]
                "tags": tagIdList, # [1367, 13224, 13225, 13226]
                # TODO: featured_media, excerpt
            }
            logging.debug("postDict=%s", postDict)
            # postDict={\'title\': \'【记录】Mac中用pmset设置GPU显卡切换模式\', \'content\': \'<html>\\n <div>\\n  折腾:\\n </div>\\n <div>\\。。。。<br/>\\n </div>\\n</html>\', \'date\': \'2020-08-17T10:16:34\', \'slug\': \'on_mac_pmset_is_used_set_gpu_graphics_card_switching_mode\', \'status\': \'draft\', \'format\': \'standard\', \'categories\': [1374], \'tags\': [1367, 13224, 13225, 13226]}
            createPostUrl = self.apiPosts
            resp = requests.post(
                createPostUrl,
                proxies=self.requestsProxies,
                headers=curHeaders,
                # data=json.dumps(postDict),
                json=postDict, # internal auto do json.dumps
            )
            logging.info("createPostUrl=%s -> resp=%s", createPostUrl, resp)
    
            isUploadOk, respInfo = crifanWordpress.processCommonResponse(resp)
            return isUploadOk, respInfo
    
    <完整(&L);最新代码请参考:

SO网友:prathamesh patil

相关推荐

安装和卸载WP-REST-API插件后API返回空白响应

WordPress/WooCommerce API在我的网站上被破坏:http://example.com/wp-json/wp/v2/posts 和http://example.com/wp-json/wc/v2/products 两者都返回空白响应。运行Python请求response = requests.get(\'http://<mysite>.com/wp-json/wp/v2/posts\', auth=HTTPBasicAuth(*auth)) 给出的响应(在调试器中