create private method for add or update media

This commit is contained in:
Valentin CZERYBA 2023-04-02 17:34:55 +02:00
parent 42b7e7e408
commit cb64dd47ab

View File

@ -53,6 +53,31 @@ class WPimport:
if r.status_code == 200:
print("Association d'une image à l'article {0}".format(title))
## Add or update img
def _addOrUpdateMedia(self, href_img):
media = {"id":"", "rendered":""}
split_fileimg = href_img.split("/")
img_name = split_fileimg[len(split_fileimg)-1]
params = { "search": img_name}
r = requests.get("http://{0}/wp-json/wp/v2/media".format(self._wordpress), auth=self._basic, params=params)
if r.status_code == 200:
res = r.json()
if len(res) == 0:
data = page.content
img_type = "image/png"
if img_name.split(".")[1]:
img_type = "image/jpg"
headers={ 'Content-Type': img_type,'Content-Disposition' : 'attachment; filename={0}'.format(img_name)}
r = requests.post("http://{0}/wp-json/wp/v2/media".format(self._wordpress), auth=self._basic, headers=headers, data=data)
if r.status_code == 201:
res = r.json()
media["id"] = res["id"]
media["rendered"] = res["guid"]["rendered"]
else:
media["id"] = res[0]["id"]
media["rendered"] = res[0]["guid"]["rendered"]
return media
## Add or Update post
@ -86,41 +111,20 @@ class WPimport:
if len(img) > 0:
href_a = i.get("href")
href_img = img[0].get("src")
page_img = requests.get(href_img)
img_break = False
new_img["old_src"]=href_img
new_img["old_href"]=href_a
page_img = requests.get(href_img)
img_break = False
if page_img.status_code == 404:
href_img = href_a
img_break = True
page = requests.get(href_img)
page = requests.get(href_a)
if page.status_code == 200:
split_fileimg = href_img.split("/")
img_name = split_fileimg[len(split_fileimg)-1]
params = { "search": img_name}
r = requests.get("http://{0}/wp-json/wp/v2/media".format(self._wordpress), auth=self._basic, params=params)
if r.status_code == 200:
res = r.json()
if len(res) == 0:
data = page.content
img_type = "image/png"
if img_name.split(".")[1]:
img_type = "image/jpg"
headers={ 'Content-Type': img_type,'Content-Disposition' : 'attachment; filename={0}'.format(img_name)}
r = requests.post("http://{0}/wp-json/wp/v2/media".format(self._wordpress), auth=self._basic, headers=headers, data=data)
if r.status_code == 201:
res = r.json()
id_res = res["id"]
rendered = res["guid"]["rendered"]
else:
id_res = res[0]["id"]
rendered = res[0]["guid"]["rendered"]
new_img["id"]=id_res
new_img["new_src"]=rendered
new_img["break"]=img_break
list_img.append(new_img)
media=self._addOrUpdateMedia(href_img)
new_img["id"]=media["id"]
new_img["new_src"]=media["rendered"]
new_img["break"]=img_break
list_img.append(new_img)
comment_post = []
for i in comment: