折腾:
【已解决】Python用WordPress的REST接口实现查询已有同名的category目录
期间,继续去优化
同时支持
- category
- Categories | REST API Handbook | WordPress Developer Resources
- tag
- Tags | REST API Handbook | WordPress Developer Resources
具体代码是:
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'} 。。。 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 searchTaxonomy(self, name, taxonomy): """Search wordpress category/tag return the exactly matched one, name is same, or name lowercase is same by call REST api: GET /wp-json/wp/v2/categories GET /wp-json/wp/v2/tags Args: name (str): category name to search taxonomy (str): taxonomy type: category/tag Returns: (bool, dict) True, found taxonomy info False, error detail Raises: """ isSearchOk = False finalRespTaxonomy = None curHeaders = { "Authorization": self.authorization, "Accept": "application/json", } logging.debug("curHeaders=%s", curHeaders) queryParamDict = { "search": name, # 'Mac' } searchTaxonomyUrl = "" if taxonomy == "category": searchTaxonomyUrl = self.apiCategories elif taxonomy == "post_tag": searchTaxonomyUrl = self.apiTags resp = requests.get( searchTaxonomyUrl, proxies=self.requestsProxies, headers=curHeaders, # data=queryDict, # {'search': 'Mac'} params=queryParamDict, # {'search': 'Mac'} ) logging.info("resp=%s for searchTaxonomyUrl=%s with queryParamDict=%s", resp, searchTaxonomyUrl, queryParamDict) isSearchOk, respTaxonomyLit = crifanWordpress.processCommonResponse(resp) logging.debug("isSearchOk=%s, respTaxonomyLit=%s", isSearchOk, respTaxonomyLit) if respTaxonomyLit: finalRespTaxonomy = crifanWordpress.findSameNameTaxonomy(name, respTaxonomyLit) logging.debug("finalRespTaxonomy=%s", finalRespTaxonomy) return isSearchOk, finalRespTaxonomy @staticmethod 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) """ 。。。 GET /wp-json/wp/v2/categories?search=Mac [ { "id": 1639, "count": 7, "description": "", "link": "https://www.crifan.com/category/work_and_job/operating_system_and_platform/mac/cocoa-mac/", "name": "Cocoa", "slug": "cocoa-mac", "taxonomy": "category", "parent": 1374, "meta": [], "_links": { "self": [{ "href": "https://www.crifan.com/wp-json/wp/v2/categories/1639" }], "collection": [{ "href": "https://www.crifan.com/wp-json/wp/v2/categories" }], "about": [{ "href": "https://www.crifan.com/wp-json/wp/v2/taxonomies/category" }], "up": [{ "embeddable": True, "href": "https://www.crifan.com/wp-json/wp/v2/categories/1374" }], "wp:post_type": [{ "href": "https://www.crifan.com/wp-json/wp/v2/posts?categories=1639" }], "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 @staticmethod def findSameNameTaxonomy(name, taxonomyLit): """Search same taxonomy (category/tag) name from taxonomy (category/tag) list Args: name (str): category/tag name to find taxonomyLit (list): category/tag list Returns: found taxonomy info (dict) Raises: """ foundTaxonomy = None sameNameTaxonomy = None lowercaseSameNameTaxonomy = None lowerName = name.lower() # 'mac' for eachTaxonomy in taxonomyLit: curTaxonomyName = eachTaxonomy["name"] # 'Cocoa', 'Mac' curTaxonomyLowerName = curTaxonomyName.lower() # 'cocoa', 'mac' if curTaxonomyName == name: sameNameTaxonomy = eachTaxonomy break elif curTaxonomyLowerName == lowerName: lowercaseSameNameTaxonomy = eachTaxonomy if sameNameTaxonomy: foundTaxonomy = sameNameTaxonomy elif lowercaseSameNameTaxonomy: foundTaxonomy = lowercaseSameNameTaxonomy return foundTaxonomy
即可也支持:
tag的查询:
搜:切换
20201204 08:59:30 crifanWordpress.py:250 INFO resp=<Response [200]> for searchTaxonomyUrl=https://www.crifan.com/wp-json/wp/v2/tags with queryParamDict={'search': '切换'}
返回:
20201204 08:59:30 crifanWordpress.py:514 INFO isOk=True, respInfo=[{'id': 6633, 'count': 1, 'description': '', 'link': 'https://www.crifan.com/tag/tab%e9%a1%b5%e9%9d%a2%e5%88%87%e6%8d%a2/', 'name': 'TAB页面切换', 'slug': 'tab%e9%a1%b5%e9%9d%a2%e5%88%87%e6%8d%a2', 'taxonomy': 'post_tag', 'meta': [], '_links': {'self': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags/6633'}], 'collection': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags'}], 'about': [{'href': 'https://www.crifan.com/wp-json/wp/v2/taxonomies/post_tag'}], 'wp:post_type': [{'href': 'https://www.crifan.com/wp-json/wp/v2/posts?tags=6633'}], 'curies': [{'name': 'wp', 'href': 'https://api.w.org/{rel}', 'templated': True}]}}, {'id': 775, 'count': 1, 'description': '', 'link': 'https://www.crifan.com/tag/%e4%b8%8d%e8%83%bd%e5%88%87%e6%8d%a2/', 'name': '不能切换', 'slug': '%e4%b8%8d%e8%83%bd%e5%88%87%e6%8d%a2', 'taxonomy': 'post_tag', 'meta': [], '_links': {'self': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags/775'}], 'collection': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags'}], 'about': [{'href': 'https://www.crifan.com/wp-json/wp/v2/taxonomies/post_tag'}], 'wp:post_type': [{'href': 'https://www.crifan.com/wp-json/wp/v2/posts?tags=775'}], 'curies': [{'name': 'wp', 'href': 'https://api.w.org/{rel}', 'templated': True}]}}, {'id': 1367, 'count': 12, 'description': '', 'link': 'https://www.crifan.com/tag/%e5%88%87%e6%8d%a2/', 'name': '切换', 'slug': '%e5%88%87%e6%8d%a2', 'taxonomy': 'post_tag', 'meta': [], '_links': {'self': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags/1367'}], 'collection': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags'}], 'about': [{'href': 'https://www.crifan.com/wp-json/wp/v2/taxonomies/post_tag'}], 'wp:post_type': [{'href': 'https://www.crifan.com/wp-json/wp/v2/posts?tags=1367'}], 'curies': [{'name': 'wp', 'href': 'https://api.w.org/{rel}', 'templated': True}]}}, {'id': 5233, 'count': 1, 'description': '', 'link': 'https://www.crifan.com/tag/%e5%88%87%e6%8d%a2%e7%89%88%e6%9c%ac/', 'name': '切换版本', 'slug': '%e5%88%87%e6%8d%a2%e7%89%88%e6%9c%ac', 'taxonomy': 'post_tag', 'meta': [], '_links': {'self': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags/5233'}], 'collection': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags'}], 'about': [{'href': 'https://www.crifan.com/wp-json/wp/v2/taxonomies/post_tag'}], 'wp:post_type': [{'href': 'https://www.crifan.com/wp-json/wp/v2/posts?tags=5233'}], 'curies': [{'name': 'wp', 'href': 'https://api.w.org/{rel}', 'templated': True}]}}, {'id': 8071, 'count': 1, 'description': '', 'link': 'https://www.crifan.com/tag/%e5%88%87%e6%8d%a2%e7%94%a8%e6%88%b7/', 'name': '切换用户', 'slug': '%e5%88%87%e6%8d%a2%e7%94%a8%e6%88%b7', 'taxonomy': 'post_tag', 'meta': [], '_links': {'self': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags/8071'}], 'collection': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags'}], 'about': [{'href': 'https://www.crifan.com/wp-json/wp/v2/taxonomies/post_tag'}], 'wp:post_type': [{'href': 'https://www.crifan.com/wp-json/wp/v2/posts?tags=8071'}], 'curies': [{'name': 'wp', 'href': 'https://api.w.org/{rel}', 'templated': True}]}}, {'id': 5734, 'count': 1, 'description': '', 'link': 'https://www.crifan.com/tag/%e5%88%87%e6%8d%a2%e7%9b%ae%e5%bd%95/', 'name': '切换目录', 'slug': '%e5%88%87%e6%8d%a2%e7%9b%ae%e5%bd%95', 'taxonomy': 'post_tag', 'meta': [], '_links': {'self': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags/5734'}], 'collection': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags'}], 'about': [{'href': 'https://www.crifan.com/wp-json/wp/v2/taxonomies/post_tag'}], 'wp:post_type': [{'href': 'https://www.crifan.com/wp-json/wp/v2/posts?tags=5734'}], 'curies': [{'name': 'wp', 'href': 'https://api.w.org/{rel}', 'templated': True}]}}, {'id': 12404, 'count': 1, 'description': '', 'link': 'https://www.crifan.com/tag/%e5%a4%a7%e5%b0%8f%e5%86%99%e5%88%87%e6%8d%a2/', 'name': '大小写切换', 'slug': '%e5%a4%a7%e5%b0%8f%e5%86%99%e5%88%87%e6%8d%a2', 'taxonomy': 'post_tag', 'meta': [], '_links': {'self': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags/12404'}], 'collection': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags'}], 'about': [{'href': 'https://www.crifan.com/wp-json/wp/v2/taxonomies/post_tag'}], 'wp:post_type': [{'href': 'https://www.crifan.com/wp-json/wp/v2/posts?tags=12404'}], 'curies': [{'name': 'wp', 'href': 'https://api.w.org/{rel}', 'templated': True}]}}, {'id': 10358, 'count': 1, 'description': '', 'link': 'https://www.crifan.com/tag/%e5%b7%a6%e5%8f%b3%e5%88%87%e6%8d%a2/', 'name': '左右切换', 'slug': '%e5%b7%a6%e5%8f%b3%e5%88%87%e6%8d%a2', 'taxonomy': 'post_tag', 'meta': [], '_links': {'self': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags/10358'}], 'collection': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags'}], 'about': [{'href': 'https://www.crifan.com/wp-json/wp/v2/taxonomies/post_tag'}], 'wp:post_type': [{'href': 'https://www.crifan.com/wp-json/wp/v2/posts?tags=10358'}], 'curies': [{'name': 'wp', 'href': 'https://api.w.org/{rel}', 'templated': True}]}}, {'id': 11537, 'count': 1, 'description': '', 'link': 'https://www.crifan.com/tag/%e5%be%aa%e7%8e%af%e5%88%87%e6%8d%a2/', 'name': '循环切换', 'slug': '%e5%be%aa%e7%8e%af%e5%88%87%e6%8d%a2', 'taxonomy': 'post_tag', 'meta': [], '_links': {'self': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags/11537'}], 'collection': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags'}], 'about': [{'href': 'https://www.crifan.com/wp-json/wp/v2/taxonomies/post_tag'}], 'wp:post_type': [{'href': 'https://www.crifan.com/wp-json/wp/v2/posts?tags=11537'}], 'curies': [{'name': 'wp', 'href': 'https://api.w.org/{rel}', 'templated': True}]}}, {'id': 5997, 'count': 1, 'description': '', 'link': 'https://www.crifan.com/tag/%e6%9d%a5%e5%9b%9e%e5%88%87%e6%8d%a2/', 'name': '来回切换', 'slug': '%e6%9d%a5%e5%9b%9e%e5%88%87%e6%8d%a2', 'taxonomy': 'post_tag', 'meta': [], '_links': {'self': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags/5997'}], 'collection': [{'href': 'https://www.crifan.com/wp-json/wp/v2/tags'}], 'about': [{'href': 'https://www.crifan.com/wp-json/wp/v2/taxonomies/post_tag'}], 'wp:post_type': [{'href': 'https://www.crifan.com/wp-json/wp/v2/posts?tags=5997'}], 'curies': [{'name': 'wp', 'href': 'https://api.w.org/{rel}', 'templated': True}]}}]
即可。
转载请注明:在路上 » 【已解决】Python用WordPress的REST接口实现查询已有同名的taxonomy分类支持category目录和tag标签