Last active
April 25, 2024 05:33
-
-
Save rririanto/346a6f9feaad8b9ff8d846e7bb76af75 to your computer and use it in GitHub Desktop.
Python Ghost Insert Posts using Admin API from Ghost Wordpress Plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests # pip install requests | |
import jwt # pip install pyjwt | |
from datetime import datetime as date | |
import json | |
import os | |
CONTENT_API = "<YOUR CONTENT API>" | |
ADMIN_API = "<YOUR ADMIN API>" | |
API_URL = "<URL ENDPOINT>" | |
JSON_PATH = "<YOUR JSON PATH>" | |
# Admin API key goes here | |
key = ADMIN_API | |
# Split the key into ID and SECRET | |
id, secret = key.split(':') | |
def post_request(data): | |
iat = int(date.now().timestamp()) | |
header = {'alg': 'HS256', 'typ': 'JWT', 'kid': id} | |
payload = { | |
'iat': iat, | |
'exp': iat + 5 * 60, | |
'aud': '/v4/admin/' | |
} | |
# Create the token (including decoding secret) | |
token = jwt.encode(payload, bytes.fromhex(secret), | |
algorithm='HS256', headers=header) | |
# Make an authenticated request to create a post | |
url = API_URL + "/ghost/api/v4/admin/posts/" | |
headers = {'Authorization': 'Ghost {}'.format(token)} | |
body = {"posts": [data]} | |
r = requests.post(url, json=body, headers=headers) | |
print(r.status_code) | |
def initiate_tags(tags): | |
params = { | |
"title": "tags", | |
"tags": tags, | |
"html": "tags", | |
} | |
post_request(params) | |
def set_tags_name(tags, list_tags): | |
post_tags = [] | |
for tag in tags: | |
if tag['id'] in list_tags: | |
post_tags.append(tag['name']) | |
return post_tags | |
def format_tags(tags): | |
for i in tags: | |
i['id'] = str(i['id']) | |
return tags | |
def initiate_data(file): | |
data = json.loads(file)['data'] | |
posts_tags = data['posts_tags'] | |
tags = format_tags(data['tags']) | |
# Initiate tags before creating post | |
initiate_tags(tags) | |
list_title = [] | |
for dt in data['posts']: | |
post_id = dt['id'] | |
# find tags with posts id | |
get_tags = list(filter(lambda x: x["post_id"] == post_id, posts_tags)) | |
if get_tags: | |
# get list of tags | |
list_tags = [str(tag['tag_id']) for tag in get_tags] | |
new_tags = set_tags_name(tags, list_tags) | |
title = dt['title'] | |
# prevent from duplicaton | |
if title not in list_title: | |
new_data = { | |
'id': dt['id'], | |
'tags': new_tags, | |
'title': dt['title'], | |
'mobiledoc': dt['mobiledoc'], | |
'html': dt['html'], | |
'feature_image': dt['feature_image'], | |
'status': dt['status'], | |
'created_at': dt['updated_at'] | |
} | |
post_request(new_data) | |
list_title.append(title) | |
if __name__ == "__main__": | |
get_json = open(JSON_PATH).read() | |
initiate_data(get_json) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment