Come usare Python per creare un Post in Wordpress?
10 feb 2019, 09:02:02
Visualizzazioni: 16.4K
Voti: 0
Ho trovato il riferimento API qui: https://v2.wp-api.org/reference/posts/
Basandomi sul riferimento API sopra, ho scritto questo codice 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': 'Il Titolo',
'author': 'L\'Autore',
'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("operazione fallita con rc=" + r.getcode())
return json.loads(r.read())
Perché quando chiamo questo codice, l'API di WP restituisce semplicemente la pagina About del sito, e non crea un nuovo Post? In che altro modo posso creare un Post all'interno di Wordpress, usando Python per chiamare l'API di WP?
Tutte le risposte alla domanda
2
0
come generare un
come dice @prathamesh patil
, hai dimenticato authentication
= il tuo jwt token
come generare un jwt token
?
- semplice = logica di base
- installa e attiva il plugin WordPress: JWT Authentication for WP REST API
- abilita
HTTP:Authorization
sul server WordPress- scopo: permettere di chiamare l'API
/wp-json/jwt-auth/v1
- scopo: permettere di chiamare l'API
- aggiungi
JWT_AUTH_SECRET_KEY
nel filewp-config.php
- chiama
POST https://www.yourWebsite.com/wp-json/jwt-auth/v1/token
conusername
epassword
di WordPress, la risposta conterrà il tuo jwt token atteso- avrà un aspetto simile a:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczpcL1wvd3d3LmNyaWZhbi5jb20iLCJpYXQiOjE1ODQxMDk4OTAsIm5iZiI6MTU4NDEwOTg5MCwiZXhwIjoxNTg0NzE0NjkwLCJkYXRhIjp7InVzZXIiOnsiaWQiOiIxIn19fQ.YvFzitTfIZaCwtkxKTIjP715795OMAVQowgnD8G3wk0
- avrà un aspetto simile a:
- dettagli
- fai riferimento alla mia risposta in un altro post:
codice Python per chiamare l'API REST di WordPress per creare post
codice:
def createPost(self,
title,
content,
dateStr,
slug,
categoryNameList=[],
tagNameList=[],
status="draft",
postFormat="standard"
):
"""Crea un post standard su WordPress
chiamando l'API REST: POST /wp-json/wp/v2/posts
Args:
title (str): titolo del post
content (str): contenuto del post in html
dateStr (str): stringa di data
slug (str): URL slug del post
categoryNameList (list): lista di nomi delle categorie
tagNameList (list): lista di nomi dei tag
status (str): stato, predefinito a 'draft'
postFormat (str): formato del post, predefinito a 'standard'
Returns:
(bool, dict)
True, informazioni del post caricato
False, dettagli dell'errore
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")
# nome categoria 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, # interno auto fa json.dumps
)
logging.info("createPostUrl=%s -> resp=%s", createPostUrl, resp)
isUploadOk, respInfo = crifanWordpress.processCommonResponse(resp)
return isUploadOk, respInfo
- per il codice completo e più recente, consulta:
createPost
in crifanWordpress.py

crifan
146
3 gen 2021 10:34:18
0
Penso tu ti stia perdendo la parte relativa all'autenticazione, dai un'occhiata qui https://stackoverflow.com/questions/41532738/publish-wordpress-post-with-python-requests-and-rest-api

prathamesh patil
1
10 feb 2019 13:15:06
Domande correlate
3
risposte
1
risposte