Created
August 19, 2021 15:08
-
-
Save nghiahsgs/303695f411188572ea5bd83c457a4e18 to your computer and use it in GitHub Desktop.
auto-create-new-image-wordpress-python
This file contains 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 | |
import base64 | |
import slugify | |
# https://github.com/WP-API/Basic-Auth => use API wpv2 | |
url = 'http://newwp.nghiahsgs.com/wp-json/wp/v2/posts' | |
def base_64_encode(message): | |
# message = "admin:password" | |
message_bytes = message.encode('ascii') | |
base64_bytes = base64.b64encode(message_bytes) | |
base64_string = base64_bytes.decode("ascii") | |
return base64_string | |
def geneate_headers_upload(username,password): | |
headers = { | |
'Authorization':'Basic %s'%base_64_encode('%s:%s'%(username,password)), | |
'Content-Disposition':'form-data; filename="ten-dep-hon.jpg"', | |
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36' | |
} | |
return headers | |
username = '' | |
password = '' | |
filepath =r'C:\Users\DELL\Desktop\avatar\avatar-1.jpg' | |
title = 'day la title 001' | |
caption = 'day la caption cua anh' | |
headers = geneate_headers_upload(username,password) | |
url = 'http://newwp.nghiahsgs.com/wp-json/wp/v2/media' | |
filename = filepath.split('\\')[-1] | |
if filename.split('.')[-1]=='png': | |
Content_Type = 'image/png' | |
if filename.split('.')[-1]=='jpg': | |
Content_Type = 'image/jpeg' | |
files = { | |
'file': (filename, open(filepath, 'rb')), | |
'Content-Type': Content_Type, | |
'Content-Length': 1 | |
} | |
dataPost = { | |
'title':title, | |
'caption':caption, | |
} | |
res = requests.post(url, data=dataPost,files = files,headers=headers,verify=False).json() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment