Python to wordpress - python

I've written this code for sending a cpt with metadata from python to WordPress, it`s one of 4 different scenarios that I have prove, practically I need to send a post with some meta field from python to WordPress using an external variable that set title and product price and product spec,
the JSON file that I need to do that asking to postman with a get request is that
[
{
"id": 3693,
"date": "2021-07-14T20:00:35",
"date_gmt": "2021-07-14T18:00:35",
"guid": {
"rendered": "http://www.mydomain.it/acme_product/spec-3/"
},
"modified": "2021-07-20T01:58:48",
"modified_gmt": "2021-07-19T23:58:48",
"slug": "spec-3",
"status": "publish",
"type": "acme_product",
"link": "http://www.mydomain.it/acme_product/spec-3/",
"title": {
"rendered": "spec"
},
"featured_media": 0,
"template": "",
"product_price": null,
"product_spec": null,
"_links": {
"self": [
{
"href": "http://www.mydomain.it/wp-json/wp/v2/acme_product/3693"
}
],
"collection": [
{
"href": "http://www.mydomain.it/wp-json/wp/v2/acme_product"
}
],
"about": [
{
"href": "http://www.mydomain.it/wp-json/wp/v2/types/acme_product"
}
],
"wp:attachment": [
{
"href": "http://www.mydomain.it/wp-json/wp/v2/media?parent=3693"
}
],
"curies": [
{
"name": "wp",
"href": "https://api.w.org/{rel}",
"templated": true
}
]
}
},
when i actually use my python code wordpress accept the post but don't fill the field for product price and product specs , some idea, what can i do with that? thanks for all
from __future__ import print_function
import base64
import sys
from datetime import datetime
import json
import requests
user= 'username'
password='auth
url = 'http://www.mydomain.it/wp-json/wp/v2/'
d= sys.argv
a_dict={}
b_dict={}
data_string = user + ':' + password
token = base64.b64encode(data_string.encode())
headers = {'Authorization': 'Basic ' + token.decode('utf-8')}
date="2021-07-14T20:00:35"
title=d[1]
slug= d[1]
status= "publish"
author="1"
##excerpt="exc post"
##format="standard"
product_price= d[2]
product_spec=d[3]
for var in ["product_price","product_spec"]:
b_dict[var]= eval(var)
print (b_dict[var])
meta= b_dict[var]
for variable in ["date", "title", "slug","status","author","product_price","product_spec"]:
a_dict[variable] = eval(variable)
r = requests.post(url + 'acme_product', headers=headers, json=a_dict)
print(r.content.decode('utf-8'))
print('Your post is published on ' + json.loads(r.content.decode('utf-8'))['link'])

Related

Error 500 when adding table to confluence page using rest api

I'm trying to add a table to a confluence page using the rest api but it returns error 500. I don't have permissions to check the server log so I'd just like to check if the issue is with my code before i ask the server admin for permissions.
`
import json
import requests
# Set the base URL for the Confluence REST API
base_url = "https://myconfluence.atlassian.net/wiki"
# Set the content ID
content_id = "30825808261"
# Set the table data
table_data = [
{
"type": "tableRow",
"content": [
{
"type": "tableCell",
"content": [
{
"type": "paragraph",
"text": "Row 1, Cell 1"
}
]
},
{
"type": "tableCell",
"content": [
{
"type": "paragraph",
"text": "Row 1, Cell 2"
}
]
}
]
},
{
"type": "tableRow",
"content": [
{
"type": "tableCell",
"content": [
{
"type": "paragraph",
"text": "Row 2, Cell 1"
}
]
},
{
"type": "tableCell",
"content": [
{
"type": "paragraph",
"text": "Row 2, Cell 2"
}
]
}
]
}
]
# Set the updated content, including the table
updated_content = {
"type": "page",
"content": [
{
"type": "paragraph"
},
{
"type": "table",
"content": table_data
}
],
"version": {
"number": 6
}
}
# Set the request headers
headers = {
"Content-Type": "application/json"
}
# Set the authentication credentials
username = 'username'
token = 'token'
auth = (username , token)
# Send the PUT request to update the content
response = requests.put(
f"{base_url}/rest/api/content/{content_id}",
headers=headers,
auth=auth,
data=json.dumps(updated_content)
)
print(updated_content)
print(response)
print(response.status_code)
# Check the status code of the response
if response.status_code == 200:
print("Content updated successfully")
else:
print("Error updating content")
`
This is the output i get:
<Response [500]>
500
Error updating content

400 Bad Request POST request

I'm programing in Python some API application, using POSTMAN, and a Bearer token. I already receive the token, and to some GET with success response.
But when doing a insert of a record I got 400 Bad request error, this is the code I'm using for adding the record
def add_identity(token, accountid, newIdentity):
end_point = f"https://identityservice-demo.clearid.io/api/v2/accounts/{accountid}/identities/"
headers = CaseInsensitiveDict()
headers["Content-type"] = "application/json; charset=utf-8"
headers["Authorization"] = f"Bearer {token}"
response = requests.request("POST", end_point, data=newIdentity, headers=headers)
print(f"{response.reason} - {response.status_code}")
the variable newIdentity has the following data
nID = {
"privateData": {
"birthday": "1985-30-11T18:23:27.955Z",
"employeeNumber": "99999999",
"secondaryEmail": "",
"cityOfResidence": "Wakanda",
"stateOfResidence": "Florida",
"zipCode": "102837",
"phoneNumberPrimary": "(999)-999-999)",
"phoneNumberSecondary": "+5-(999)-999-9999"
},
"companyData": {
"approvers": [
{
"approverId": ""
}
],
"supervisorName": "Roger Rabbit",
"departmentName": "Presidency",
"jobTitle": "President",
"siteId": "string",
"companyName": "ACME Inc",
"workerTypeDescription": "",
"workerTypeCode": ""
},
"systemData": {
"hasExtendedTime": "true",
"activationDateUtc": "2022-03-16T18:23:27.955Z",
"expirationDateUtc": "2022-03-16T18:23:27.955Z",
"externalId": "999999",
"externalSyncTimeUtc": "2022-03-16T18:23:27.955Z",
"provisioningAttributes": [
{
"name": ""
}
],
"customFields": [
{
"customFieldType": "string",
"customFieldName": "SSNO",
"customFieldValue": "9999999"
}
]
},
"nationalIdentities": [
{
"nationalIdentityNumber": "0914356777",
"name": "Passport",
"issuer": "Wakanda"
}
],
"description": "1st Record ever",
"status": "Active",
"firstName": "Bruce",
"lastName": "Wayne",
"middleName": "Covid",
"displayName": "Bruce Wayne",
"countryCode": "WK",
"email": "bruce.wayne#wakanda.com",
"creationOnBehalf": "ACME"
}
what could solve the problem?
the swagger for the API is
https://identityservice-demo.clearid.io/swagger/index.html#/Identities/get_api_v2_accounts__accountId__identities
Thanks for your help in advance
data have to be a dict ,, you can try import json and data=json.dumps(newIdentity) ,
and if it keeps returning 400 , check well that all the parameters are accepted by the api by recreating the request with Postman or any request editor, and if the api uses any web interface check what is the reason for that 400 . This was translated by Google so I don't know if I said something nonsense :)

Get data from Pendo via Python api call

There are some reports created in Pendo (Like adobe ) . I want to pull this report via python api call .
I have written code which is partially incorrect .Please let me know what I'm doing wrong?
The output should be in form of table which contains 4 columns and their records.
This code is only returning - {'overall': {}, 'fields': {'pipeline': 'Required'}}
Which is strange.
pendo_key='123fgh21-ab89-ab23-21ad-bvh3r11r2sv5.ca'
import matplotlib.pyplot as pt
import pandas as pd
import numpy as np
import requests
import os
import json
import pandas as pd
from io import StringIO
pd.set_option('display.max_colwidth',0)
url= "https://app.pendo.io/api/v1/aggregation"
headers = {
'X-Pendo-Integration-Key':pendo_key,
'Content-Type':'application/json'}
payload1= json.dumps({
"response": {
"location": "request",
"mimeType": "application/json"
},
"requests": [
{
"name": "SalesEventAggregation",
"pipeline": [
{
"source": {
"salesEvents": {
"blacklist": "apply",
"salesTypeId": "dg_5w_fgtdergJ67vFdfR8kWsxi"
},
"timeSeries": {
"period": "dayRange",
"first": "now()",
"count": 1
}
}
}],
"requestId": "saleseventAggregation-rId-etr1231-561s-6d6c-7d12-351f1d21gww2"
}
]
})
response = requests.request("POST",url,headers=headers, data= payload1)
print("Status code:", response.status_code)
response_dict = json.loads(response.text)
response_dict
Status code: 422
Output:
{'overall': {}, 'fields': {'pipeline': 'Required'}}
Expected:
There are 4 columns in form of table which is not showing up and their relevant records is not showing up.
The "request" object is not an array, and the "key" should be named as "request"(singular) not as "requests"(plural).
Try
payload1= json.dumps(
{
"response": {
"location": "request",
"mimeType": "application/json"
},
"request":
{
"name": "SalesEventAggregation",
"pipeline": [
{
"source": {
"salesEvents": {
"blacklist": "apply",
"salesTypeId": "dg_5w_fgtdergJ67vFdfR8kWsxi"
},
"timeSeries": {
"period": "dayRange",
"first": "now()",
"count": 1
}
}
}],
"requestId": "saleseventAggregation-rId-etr1231-561s-6d6c-7d12-351f1d21gww2"
}
})

How to get a value from JSON

This is the first time I'm working with JSON, and I'm trying to pull url out of the JSON below.
{
"name": "The_New11d112a_Company_Name",
"sections": [
{
"name": "Products",
"payload": [
{
"id": 1,
"name": "TERi Geriatric Patient Skills Trainer,
"type": "string"
}
]
},
{
"name": "Contact Info",
"payload": [
{
"id": 1,
"name": "contacts",
"url": "https://www.a3bs.com/catheterization-kits-8000892-3011958-3b-scientific,p_1057_31043.html",
"contacts": [
{
"name": "User",
"email": "Company Email",
"phone": "Company PhoneNumber"
}
],
"type": "contact"
}
]
}
],
"tags": [
"Male",
"Airway"
],
"_id": "0e4cd5c6-4d2f-48b9-acf2-5aa75ade36e1"
}
I have been able to access description and _id via
data = json.loads(line)
if 'xpath' in data:
xpath = data["_id"]
description = data["sections"][0]["payload"][0]["description"]
However, I can't seem to figure out a way to access url. One other issue I have is there could be other items in sections, which makes indexing into Contact Info a non starter.
Hope this helps:
import json
with open("test.json", "r") as f:
json_out = json.load(f)
for i in json_out["sections"]:
for j in i["payload"]:
for key in j:
if "url" in key:
print(key, '->', j[key])
I think your JSON is damaged, it should be like that.
{
"name": "The_New11d112a_Company_Name",
"sections": [
{
"name": "Products",
"payload": [
{
"id": 1,
"name": "TERi Geriatric Patient Skills Trainer",
"type": "string"
}
]
},
{
"name": "Contact Info",
"payload": [
{
"id": 1,
"name": "contacts",
"url": "https://www.a3bs.com/catheterization-kits-8000892-3011958-3b-scientific,p_1057_31043.html",
"contacts": [
{
"name": "User",
"email": "Company Email",
"phone": "Company PhoneNumber"
}
],
"type": "contact"
}
]
}
],
"tags": [
"Male",
"Airway"
],
"_id": "0e4cd5c6-4d2f-48b9-acf2-5aa75ade36e1"
}
You can check it on http://json.parser.online.fr/.
And if you want to get the value of the url.
import json
j = json.load(open('yourJSONfile.json'))
print(j['sections'][1]['payload'][0]['url'])
I think it's worth to write a short function to get the url(s) and make a decision whether or not to use the first found url in the returned list, or skip processing if there's no url available in your data.
The method shall looks like this:
def extract_urls(data):
payloads = []
for section in data['sections']:
payloads += section.get('payload') or []
urls = [x['url'] for x in payloads if 'url' in x]
return urls
This should print out the URL
import json
# open json file to read
with open('test.json','r') as f:
# load json, parameter as json text (file contents)
data = json.loads(f.read())
# after observing format of JSON data, the location of the URL key
# is determined and the data variable is manipulated to extract the value
print(data['sections'][1]['payload'][0]['url'])
The exact location of the 'url' key:
1st (position) of the array which is the value of the key 'sections'
Inside the array value, there is a dict, and the key 'payload' contains an array
In the 0th (position) of the array is a dict with a key 'url'
While testing my solution, I noticed that the json provided is flawed, after fixing the json flaws(3), I ended up with this.
{
"name": "The_New11d112a_Company_Name",
"sections": [
{
"name": "Products",
"payload": [
{
"id": 1,
"name": "TERi Geriatric Patient Skills Trainer",
"type": "string"
}
]
},
{
"name": "Contact Info",
"payload": [
{
"id": 1,
"name": "contacts",
"url": "https://www.a3bs.com/catheterization-kits-8000892-3011958-3b-scientific,p_1057_31043.html",
"contacts": [
{
"name": "User",
"email": "Company Email",
"phone": "Company PhoneNumber"
}
],
"type": "contact"
}
]
}
],
"tags": [
"Male",
"Airway"
],
"_id": "0e4cd5c6-4d2f-48b9-acf2-5aa75ade36e1"}
After utilizing the JSON that was provided by Vincent55.
I made a working code with exception handling and with certain assumptions.
Working Code:
## Assuming that the target data is always under sections[i].payload
from json import loads
line = open("data.json").read()
data = loads(line)["sections"]
for x in data:
try:
# With assumption that there is only one payload
if x["payload"][0]["url"]:
print(x["payload"][0]["url"])
except KeyError:
pass

Paging using json file in python

I have this json file which includes information about pages I have retrieving using this
python code:
import facebook # pip install facebook-sdk
import json
import codecs
# Create a connection to the Graph API with your access token
ACCESS_TOKEN = ''#my access token
g = facebook.GraphAPI(ACCESS_TOKEN)
s=g.request('search', { 'q' : '&','type' : 'page', 'limit' : 5000 , 'locale' : 'ar_AR' })
f = open("sampels.txt", 'w')
f.write(json.dumps(s, indent=1))
f.close()
#########################################################
this is my samples json file a snapshot of it:
{
"paging": {
"next": "https://graph.facebook.com/search?limit=5000&type=page&q=%26&locale=ar_AR&access_token=CAACEdEose0cBAIRlSOXkyk1lIMUIWViAoz5lf5t0pSdsu6lg5ZANJuYMIPZCy5N9KFQoLnpi1oxD8tNIaabWackCO31UYaAGkb38IPHxI33ldbRQDXJ02CtJrwE8NI4mZAz20OznLfuCpypDbxNYF3p9XauZCtoywoS9KJwAgW8NYgZCpD4ZBKfCBR5jjXnbcZD&offset=5000&__after_id=92240239536"
},
"data": [
{
"category": "\u0627\u0644\u062a\u0639\u0644\u064a\u0645",
"name": "The London School of Economics and Political Science - LSE",
"category_list": [
{
"id": "108051929285833",
"name": "\u0627\u0644\u0643\u0644\u064a\u0629 \u0648\u0627\u0644\u062c\u0627\u0645\u0639\u0629"
},
{
"id": "187751327923426",
"name": "\u0645\u0646\u0638\u0645\u0629 \u062a\u0639\u0644\u064a\u0645\u064a\u0629"
}
],
"id": "6127898346"
},
{
"category": "\u0628\u0636\u0627\u0626\u0639 \u0627\u0644\u0628\u064a\u0639 \u0628\u0627\u0644\u062a\u062c\u0632\u0626\u0629 \u0648\u0628\u0636\u0627\u0626\u0639 \u0627\u0644\u0645\u0633\u062a\u0647\u0644\u0643\u064a\u0646",
"name": "Stop & Shop",
"category_list": [
{
"id": "169207329791658",
"name": "\u0645\u062d\u0644 \u0628\u0642\u0627\u0644\u0629"
}
],
"id": "170000993071234"
},
{
"category": "\u0628\u0636\u0627\u0626\u0639 \u0627\u0644\u0628\u064a\u0639 \u0628\u0627\u0644\u062a\u062c\u0632\u0626\u0629 \u0648\u0628\u0636\u0627\u0626\u0639 \u0627\u0644\u0645\u0633\u062a\u0647\u0644\u0643\u064a\u0646",
"name": "C&A",
"category_list": [
{
"id": "186230924744328",
"name": "\u0645\u062a\u062c\u0631 \u0645\u0644\u0627\u0628\u0633"
}
],
"id": "109345009145382"
},
{
"category": "\u0645\u0646\u0638\u0645\u0629 \u063a\u064a\u0631 \u0631\u0628\u062d\u064a\u0629",
"name": "Rock and Roll Hall of Fame + Museum",
"category_list": [
{
"id": "396255327112122",
"name": "\u0645\u062a\u062c\u0631 \u0645\u0648\u0633\u064a\u0642\u0649"
},
now what I want to do is to get the next field in order to get my next 5000 page into my database.
I have tried a lot but I couldn't figure out away to do this can any body tell me how to take the next URL and how pass it to the request function I have in my code.?
g.request() returns a Python dict which gives you access to the paging/next url. Why do you dump it as json and write it to file instead of just using it ?

Categories

Resources