I hope your are fine.
I would like to upload an image in my wordpress library from my computer.
I wrote few lines in Python that use Wordpress API.
It is working when I use 'Content-Type': 'application/x-www-form-urlencoded'
However, the content added is not an image.
When I change it with 'Content-Type': 'image/jpg' I get an error message which says:
Error 403 please forward this error screen to the site owner
What should I do, contact my web hosting company ?
Thank you all for you help
Here is my code:
from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
import base64
import json
import time
import os
user = "user"
password = "pass"
url = "https://example.com/wp-json/wp/v2"
data_string = user + ':' + password
token = base64.b64encode(data_string.encode())
# headers={'Authorization': 'Basic ' + token.decode('utf-8'), 'Content-Type': 'image/jpg','Content-Disposition' : 'attachment; filename=%s'% "test.jpg"}
headers={'Authorization': 'Basic ' + token.decode('utf-8'), 'Content-Type': 'application/x-www-form-urlencoded','Content-Disposition' : 'attachment; filename=%s'% "test.jpg"}
video = {
"title": "test",
"description": "description",
"media-type": "image",
}
r = requests.post(url + "/media", headers=headers, json=video)
print(r.text)
I solved the problem with this code
from requests_toolbelt.multipart.encoder import MultipartEncoder
import requests
import base64
import json
import time
import os
user = "user"
password = "pass"
url = "https://example.com/wp-json/wp/v2"
data_string = user + ':' + password
token = base64.b64encode(data_string.encode())
headers = {'Authorization': 'Basic ' + token.decode('utf-8')}
image = {
"file": open("toto.png", "rb"),
"caption": "caption",
"description": "description",
}
r = requests.post(url + "/media", headers=headers, files=image)
print(r.text)
print(r)
Related
I want to get content in Confluence with specific-page (pageID).
I've the script below:
import base64
import requests
import browser_cookie3
personal_access_token = "PATcode"
organizational_url = "https://confluence.fake-site.com/"
authorization = personal_access_token
headers = { 'Accept': 'application/json', 'Authorization': 'Bearer '+authorization }
confluence_url = organizational_url+'rest/api/content/pageID'
proxiesX = {
'http': '11.22.33.44:8080'
}
cookies = browser_cookie3.chrome(domain_name='.confluence.fake-site.com')
print(cookies)
response = requests.get(url=confluence_url, headers=headers, proxies = proxiesX, cookies=cookies, verify=False)
#print(response.status_code)
print(response.text)
My pageID has a content like this: "ABCDEF".
But upper script return output is un-structure HTML content with some context similar with "Unable to sign in, login failed..."
Can anyone help me to define where to fix?
Expecting output after running script: "ABCDEF" which is pageID's content
I integrate requests_toolbelt with Google Photos api, the video file does not open even though the file is the same size.
The video upload process is successful, but the video is corrupted and cannot be opened. It gives 0xc00d36c4 error.
import os
import pickle
import requests
from requests_toolbelt import MultipartEncoder
import requests
url = 'https://photoslibrary.googleapis.com/v1/uploads'
token = pickle.load(open('token.pickle', 'rb'))
headers = {
'Authorization': 'Bearer ' + token.token,
'Content-type': 'application/octet-stream',
'X-Goog-Upload-Protocol' : 'raw',
'X-Goog-Upload-File-Name' : 'test.mp4'
}
media = MultipartEncoder(fields = {'file': open('test.mp4', 'rb')})
response = requests.post(url, data=media, headers=headers)
request_body = {
'newMediaItems': [
{
'simpleMediaItem': {
'uploadToken': response.content.decode('utf-8')
}
}
]
}
upload_response = service.mediaItems().batchCreate(body=request_body).execute()
I am following a simple example (or what I thought was simple) of creating a python script that used the REST api to connect to wordpress.
However, I am getting a 403 error. My credentials are correct because I can log in with them.
I have been working over this for awhile now. Can anyone see where my error might be? Thank you.
url = "https://prod-wp.xxxxxx.com/wp-json/wp/v2/posts"
user = "xxxxxx"
password = "xxxxxxxx"
credentials = user + ':' + password
token = base64.b64encode(credentials.encode())
header = {'Authorization': 'Basic ' + token.decode('utf-8')}
response = requests.get(url , headers=header)
print(response)
<Response [403]>
EDIT
I have changed the code and this seems to work.
import requests
import os
from dotenv import load_dotenv
load_dotenv()
BASE_URL = 'https://website.com/wp-json'
WP_URL = os.getenv("WP_URL")
WP_USERNAME = os.getenv("WP_USERNAME")
WP_PASSWORD = os.getenv("WP_PASSWORD")
def get_headers():
wp_credentials = {'username': WP_USERNAME, 'password': WP_PASSWORD}
jwt_response = requests.post(f'{BASE_URL}/jwt-auth/v1/token', json=wp_credentials)
jwt_token = jwt_response.json()['token']
headers = {
"Authorization": "Bearer %s" % jwt_token,
"Content-Type": "application/json",
"Accept": "application/json",
}
print(f'Headers are equal to: {headers}')
return headers
get_headers()
I am using the python code below to upload a file to our marketing automation tool Marketo. It works when I have the file downloaded locally (/home/tyron/Downloads/yoda.jpeg) but I would like to be able to upload a file straight from Dropbox to Marketo without having to download it inbetween because I will be hosting this code in Zapier.
What is the best way to do this upload when given a link to the dropbox file?
import requests
url = "xxxxxx/rest/asset/v1/files.json"
payload = {'name': 'test',
'file': '/home/tyron/Downloads/yoda.jpe',
'folder': '{"id":367,"type":"Folder"}'}
files = [
('file', open('/home/tyron/Downloads/yoda.jpeg','rb'))
]
headers = {
'Authorization': 'Bearer yyyyyyyy'
}
response = requests.request("POST", url, headers=headers, data = payload, files = files)
print(response.text.encode('utf8'))
Thanks to Greg's suggestion in the comments I was able to upload the file to Marketo using the temporary link endpoint from dropbox.
Python Code to Get Dropbox Endpoint
import re
from urllib.parse import urlparse
from urllib.parse import unquote
import requests
import json
link = "https://www.dropbox.com/preview/Telnyx/...../file"
path = urlparse(link).path
path = re.search("(/Telnyx.*$)",path).group(0).lower()
path = unquote(path)
print(path)
url = "https://api.dropboxapi.com/2/files/get_temporary_link"
payload = {"path": path}
headers = {
'Authorization': 'Bearer xxxxxxxxxxxxxx',
'Content-Type': 'application/json'
}
response = requests.request("POST", url, headers=headers, data = json.dumps(payload))
print(response)
link = re.search('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_#.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', response.text).group(0)
return {'id': 1234, 'rawHTML': link}
Python Code to Upload to Marketo
import requests
import urllib
import json
import re
path = "https://dl.dropboxusercontent.com/apitl/1/......." #returned from previous function
f = urllib.request.urlopen(path)
mime_type = f.info().get_content_type()
f_ext = f.info().get_content_type().split("/")[1]
url = "https://xxx-xxx-xxx.mktorest.com/rest/asset/v1/files.json"
f_name = 'Name.' + f_ext
payload = {
'folder': '{"id":xxxx","type":"Folder"}'
}
headers = {
'Authorization': 'Bearer xxxxxxxx'
}
files = {'file': (f_name, f, mime_type)}
response = requests.request("POST", url, headers=headers, data = payload, files = files)
print(response.text.encode('utf8'))
f_url = re.search('"url":"(.*)","folder',response.text).group(1)
return {'id': 1234, 'rawHTML': f_url}
i'm working on settin up a rest api with python, however i'm having some problem getting it to work.
I'm working with the TV DB rest api: https://api.thetvdb.com/swagger
and using python with Requests library to pull out the information.
My code is currently:
import json
import requests
URL = "https://api.thetvdb.com/"
API_KEY = "Api_key"
USER_KEY = "Key"
USERNAME = "Name"
headers = {"Accept": "application/json"}
params = {
"apikey": API_KEY,
"userkey": USER_KEY,
"username": USERNAME
}
resp = requests.post(URL + "login/", headers = headers ,params=params)
if resp.status_code != 200:
print('error: ' + str(resp.status_code))
else:
print('Success')
So far i'm only getting error code 401, not sure why.
Solved:
2 Things needed to be changed
1. The resp was changed into:
resp = requests.post(URL + "login/", headers = headers, data=json.dumps(params))
The header had to have
"Content-Type": "application/json"
added to it :) It's now working, thanks everyone
The login parameters probably need to be a JSON-encoded string POSTed as the body of the message.
Try resp = requests.post(URL + "login/", headers = headers, data=json.dumps(params))