最新消息:20210917 已从crifan.com换到crifan.org

【已解决】Python调用WordPress的REST接口新建Taxonomy分类包括category目录和tag标签

Python crifan 550浏览 0评论
折腾:
【已解决】Python调用WordPress的REST接口新建Category目录
之后,继续去优化。
继续去优化代码,支持同时创建category目录和tag标签的taxonomy分类
代码写好了
带后续完整验证功能是否完备
验证后,可以创建:
后续代码有微调。
最后是:
class crifanWordpress(object):
    """Use Python operate WordPress via REST api

        Posts | REST API Handbook | WordPress Developer Resources
        https://developer.wordpress.org/rest-api/reference/posts/#schema-comment_status

        taxonomy = category / post_tag / nav_menu / link_category / post_format
            Categories | REST API Handbook | WordPress Developer Resources
            https://developer.wordpress.org/rest-api/reference/categories/

            Tags | REST API Handbook | WordPress Developer Resources
            https://developer.wordpress.org/rest-api/reference/tags/
    """

    def __init__(self, host, jwtToken, requestsProxies=None):
        self.host = host # 'https://www.crifan.com'
        self.authorization = "Bearer %s" % jwtToken # 'Bearer xxx'
        self.requestsProxies = requestsProxies # {'http': 'http://127.0.0.1:58591', 'https': 'http://127.0.0.1:58591'}


        # https://developer.wordpress.org/rest-api/reference/media/
        self.apiMedia = self.host + "/wp-json/wp/v2/media" # 'https://www.crifan.com/wp-json/wp/v2/media'
        # https://developer.wordpress.org/rest-api/reference/posts/
        self.apiPosts = self.host + "/wp-json/wp/v2/posts" # 'https://www.crifan.com/wp-json/wp/v2/posts'
        # https://developer.wordpress.org/rest-api/reference/categories/#create-a-category
        self.apiCategories = self.host + "/wp-json/wp/v2/categories" # 'https://www.crifan.com/wp-json/wp/v2/categories'
        # https://developer.wordpress.org/rest-api/reference/tags/#create-a-tag
        self.apiTags = self.host + "/wp-json/wp/v2/tags" # 'https://www.crifan.com/wp-json/wp/v2/tags'


    def createTaxonomy(self, name, taxonomy, parent=None, slug=None, description=None):
        """Create wordpress taxonomy(category/tag)
            by call REST api: 
                POST /wp-json/wp/v2/categories
                POST /wp-json/wp/v2/tags


        Args:
            name (str): category name
            taxonomy (str): type: category/tag
            parent (int): category parent
            slug (str): category slug
            description (str): category description
        Returns:
            (bool, dict)
                True, uploaded category info
                False, error detail
        Raises:
        """
        curHeaders = {
            "Authorization": self.authorization,
            "Content-Type": "application/json",
            "Accept": "application/json",
        }
        logging.debug("curHeaders=%s", curHeaders)
        # curHeaders={'Authorization': 'Bearer eyxxx9.eyxxxfQ.5Ixxxm-6Yxxxs', 'Content-Type': 'application/json', 'Accept': 'application/json'}


        postDict = {
            "name": name, #
        }


        if slug:
            postDict["slug"] = slug


        if description:
            postDict["description"] = description


        if taxonomy == "category":
            if parent:
                postDict["parent"] = parent


        logging.info("postDict=%s", postDict)
        # postDict={'name': 'Mac'}
        # postDict={'name': 'GPU'}


        createTaxonomyUrl = ""
        if taxonomy == "category":
            createTaxonomyUrl = self.apiCategories
        elif taxonomy == "post_tag":
            createTaxonomyUrl = self.apiTags


        resp = requests.post(
            createTaxonomyUrl,
            proxies=self.requestsProxies,
            headers=curHeaders,
            json=postDict,
        )
        logging.info("createTaxonomyUrl=%s -> resp=%s", createTaxonomyUrl, resp)
        # {'id': 13223, 'count': 0, 'description': '', 'link': 'https://www.crifan.com/category/mac-2/', 'name': 'Mac', 'slug': 'mac-2', 'taxonomy': 'category', 'parent': 0, 'meta': [], '_links': {'self': [{'href': 'https://www.crifan.com/wp-json/wp/v2/categories/13223'}], 'collection': [{'href': 'https://www.crifan.com/wp-json/wp/v2/categories'}], 'about': [{'href': 'https://www.crifan.com/wp-json/wp/v2/taxonomies/category'}], 'wp:post_type': [{'href': 'https://www.crifan.com/wp-json/wp/v2/posts?categories=13223'}], 'curies': [{'name': 'wp', 'href': 'https://api.w.org/{rel}', 'templated': True}]}}


        isCreateOk, respInfo = crifanWordpress.processCommonResponse(resp)
        logging.info("isCreateOk=%s, respInfo=%s", isCreateOk, respInfo)
        # isCreateOk=True, respInfo={'id': 13224, 'slug': 'gpu', 'link': 'https://www.crifan.com/tag/gpu/', 'name': 'GPU', 'description': ''}


        return isCreateOk, respInfo
其中:
    def processCommonResponse(resp):
        """Process common wordpress POST response for 
            POST /wp-json/wp/v2/media
            POST /wp-json/wp/v2/posts
            POST /wp-json/wp/v2/categories
            GET  /wp-json/wp/v2/categories


        Args:
            resp (Response): requests response
        Returns:
            (bool, dict)
                True, created/searched item info
                False, error detail
        Raises:
        """
        isOk, respInfo = False, {}


        if resp.ok:
            respJson = resp.json()
            logging.debug("respJson=%s", respJson)
            """
。。。

            POST /wp-json/wp/v2/categories
                {
                    "id": 13223,
                    "count": 0,
                    "description": "",
                    "link": "https://www.crifan.com/category/mac-2/",
                    "name": "Mac",
                    "slug": "mac-2",
                    "taxonomy": "category",
                    "parent": 0,
                    "meta": [],
                    "_links": {
                        "self": [{
                        "href": "https://www.crifan.com/wp-json/wp/v2/categories/13223"
                        }],
                        "collection": [{
                        "href": "https://www.crifan.com/wp-json/wp/v2/categories"
                        }],
                        "about": [{
                        "href": "https://www.crifan.com/wp-json/wp/v2/taxonomies/category"
                        }],
                        "wp:post_type": [{
                        "href": "https://www.crifan.com/wp-json/wp/v2/posts?categories=13223"
                        }],
                        "curies": [{
                        "name": "wp",
                        "href": "https://api.w.org/{rel}",
                        "templated": True
                        }]
                    }
                }
。。。
            """
            if isinstance(respJson, dict):
                isOk = True


                newId = respJson["id"]
                newSlug = respJson["slug"]
                newLink = respJson["link"]
                logging.info("newId=%s, newSlug=%s, newLink=%s", newId, newSlug, newLink)
                respInfo = {
                    "id": newId, # 70393
                    "slug": newSlug, # f6956c30ef0b475fa2b99c2f49622e35
                    "link": newLink, # https://www.crifan.com/f6956c30ef0b475fa2b99c2f49622e35/
                }


                if "type" in respJson:
                    curType = respJson["type"]
                    if (curType == "attachment") or (curType == "post"):
                        respInfo["url"] = respJson["guid"]["rendered"]
                        # "url": newUrl, # https://www.crifan.com/files/pic/uploads/2020/03/f6956c30ef0b475fa2b99c2f49622e35.png
                        respInfo["title"] = respJson["title"]["rendered"]
                        # "title": newTitle, # f6956c30ef0b475fa2b99c2f49622e35
                        logging.info("url=%s, title=%s", respInfo["url"], respInfo["title"])


                if "taxonomy" in respJson:
                    curTaxonomy = respJson["taxonomy"]
                    # common for category/tag
                    respInfo["name"] = respJson["name"]
                    respInfo["description"] = respJson["description"]
                    logging.info("name=%s, description=%s", respInfo["name"], respInfo["description"])


                    if curTaxonomy == "category":
                        respInfo["parent"] = respJson["parent"]
                        logging.info("parent=%s", respInfo["parent"])
            elif isinstance(respJson, list):
                isOk = True
                respInfo = respJson
        else:
            isOk = False
            # respInfo = resp.status_code, resp.text
            respInfo = {
                "errCode": resp.status_code,
                "errMsg": resp.text,
            }


        logging.info("isOk=%s, respInfo=%s", isOk, respInfo)
        return isOk, respInfo
可以创建tag的:
进去可以看到详情:
{'_links': {'about': [...], 'collection': [...], 'curies': [...], 'self': [...], 'wp:post_type': [...]}, 'count': 0, 'description': '', 'id': 13225, 'link': 'https://www.crifan.c...tag/pmset/', 'meta': [], 'name': 'pmset', 'slug': 'pmset', 'taxonomy': 'post_tag'}
相关log:
20201204 09:53:07 crifanWordpress.py:193  INFO    postDict={'name': 'pmset'}
20201204 09:54:18 crifanWordpress.py:209  INFO    createTaxonomyUrl=https://www.crifan.com/wp-json/wp/v2/tags -> resp=<Response [201]>
20201204 09:54:32 crifanWordpress.py:563  INFO    newId=13225, newSlug=pmset, newLink=https://www.crifan.com/tag/pmset/
20201204 09:54:47 crifanWordpress.py:584  INFO    name=pmset, description=
20201204 09:55:47 crifanWordpress.py:600  INFO    isOk=True, respInfo={'id': 13225, 'slug': 'pmset', 'link': 'https://www.crifan.com/tag/pmset/', 'name': 'pmset', 'description': ''}
供参考。

转载请注明:在路上 » 【已解决】Python调用WordPress的REST接口新建Taxonomy分类包括category目录和tag标签

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
95 queries in 0.656 seconds, using 23.44MB memory