#5 cleanup code
This commit is contained in:
3
.gitiginore
Normal file
3
.gitiginore
Normal file
@ -0,0 +1,3 @@
|
||||
.venv
|
||||
__pycache__
|
||||
logs
|
||||
212
api.py
212
api.py
@ -1,212 +0,0 @@
|
||||
from woocommerce import API
|
||||
import pandas as pd
|
||||
import ezodf
|
||||
import requests
|
||||
import pprint
|
||||
|
||||
wcapi = API(
|
||||
url="https://lescreationsdemissbleue.local",
|
||||
consumer_key="ck_604e9b7b5d290cce72346efade6b31cb9a1ff28e",
|
||||
consumer_secret="cs_563974c7e59532c1ae1d0f8bbf61f0500d6bc768",
|
||||
wp_api=True,
|
||||
version="wc/v3",
|
||||
verify_ssl=False # Désactive la vérification SSL pour le développement
|
||||
)
|
||||
|
||||
|
||||
"""
|
||||
'images': [
|
||||
{'src':'https://lescreationsdemissbleue.local/wp-content/uploads/2025/02/chope-citron-meringue-face.jpg'},
|
||||
{'src':'https://lescreationsdemissbleue.local/wp-content/uploads/2025/02/chope-citron-meringue-haut.jpg'},
|
||||
]
|
||||
{'alt': '',
|
||||
'date_created': '2025-01-16T17:22:38',
|
||||
'date_created_gmt': '2025-01-16T16:22:38',
|
||||
'date_modified': '2025-01-16T17:22:38',
|
||||
'date_modified_gmt': '2025-01-16T16:22:38',
|
||||
'name': 'Chope citron meringué (3)',
|
||||
'src': 'https://lescreationsdemissbleue.local/wp-content/uploads/2025/02/chope-citron-meringue-dos.jpg'}"""
|
||||
|
||||
"""import requests
|
||||
|
||||
url = "https://lescreationsdemissbleue.local/wp-json/wp/v2/media?media_type=image"
|
||||
response = requests.get(url, verify=False) # note: verify=False pour bypasser le certificat auto-signé en local
|
||||
images = response.json()
|
||||
print(images)
|
||||
pprint.pprint(response.json())
|
||||
|
||||
"""
|
||||
|
||||
"""data = {
|
||||
'images' : [
|
||||
{'id':610},#,'src':'https://lescreationsdemissbleue.local/wp-content/uploads/2025/02/chope-citron-meringue-face.jpg'},
|
||||
{'id':609},#'src':'https://lescreationsdemissbleue.local/wp-content/uploads/2025/02/chope-citron-meringue-haut.jpg'},
|
||||
{'id':608},
|
||||
],
|
||||
}"""
|
||||
|
||||
"""data = {
|
||||
'description': ""La Chope au parfum citron meringué est une véritable œuvre d'art, entièrement fabriquée à la main avec soin et précision, tant par le verre qui a été réalisé par un artisan verrier à Montauroux dans le Sud de la France, que par la bougie elle-même qui est faite avec passion par mes soins.
|
||||
Cette bougie offre une expérience olfactive unique, combinant les notes sophistiquées des parfums de Grasse avec la fraîcheur acidulée du citron meringué. Parfaite pour créer une ambiance chaleureuse et accueillante, elle diffuse un parfum délicat et fruité qui enveloppera votre intérieur. Que ce soit pour une soirée relaxante ou pour ajouter une touche originale à votre décoration, cette bougie est un choix raffiné qui séduira vos sens et émerveillera vos invités.
|
||||
La couleur jaune est associée à la joie, à la gaieté et à la fête. Elle est la couleur de l'amitié, des relations sociales ou encore de la fraternité. Le jaune peut aussi faire référence à la douceur et à la fraîcheur. Il est associé au bien-être et à la bonne humeur et transmet un côté ludique et rafraîchissant.
|
||||
Si vous souhaitez apporter une touche ensoleillée et acidulée à votre intérieur cette chope est faite pour vous.
|
||||
Parfum de Grasse
|
||||
Sans CMR
|
||||
Sans phtalates
|
||||
Non testé sur des animaux
|
||||
|
||||
Mèche en coton"",
|
||||
'regular_price': '36.00',
|
||||
'price': '36.00',
|
||||
'stock_quantity':1,
|
||||
'weight':'0.895'
|
||||
}"""
|
||||
|
||||
data = {
|
||||
"meta_data": [
|
||||
{
|
||||
"key": "conseil_utilisation",
|
||||
"value": """- Allumez la bougie et laissez un puits se creuser autour de la mèche afin que l'odeur se diffuse. Ne dépassez pas les 3h continues de brûlage.
|
||||
- La cire de soja se nettoie facilement avec de l’eau chaude, vous pourrez ainsi récupérer le contenant après avoir consumé toute la bougie,
|
||||
- Toutes les bougies disposent d’étiquettes de sécurité, merci d’en prendre connaissance avant d’allumer le produit.
|
||||
- La bougie brûlera environ 38 heures."""
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
response = wcapi.get("products/199")
|
||||
if response.status_code == 200:
|
||||
#wcapi.put("products/categories/199", data).json()
|
||||
#wcapi.put("products/199", data)
|
||||
#pprint.pprint(response.json())
|
||||
#response = wcapi.put("products/199", data)
|
||||
#pprint.pprint(response.json())
|
||||
pass
|
||||
else:
|
||||
print("Erreur lors de la connexion :", response.text)
|
||||
|
||||
#print(wcapi.get("categorie/bougie-chope-de-biere/").json())
|
||||
|
||||
"""category_data = {
|
||||
"name": "Bougies Parfumées",
|
||||
"description": "Collection de bougies artisanales aux parfums uniques.",
|
||||
"parent": 0,
|
||||
"image": {"src": "C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\pyramide_olfactive.png"},
|
||||
"alt":"Bougie parfumées artisanale",
|
||||
"name":"Bougie parfumées artisanale",
|
||||
|
||||
}"""
|
||||
|
||||
import base64
|
||||
|
||||
# ✅ Générer l'authentification Basic en Base64 avec `consumer_key` et `consumer_secret`
|
||||
auth_str = wcapi.consumer_key
|
||||
auth_bytes = auth_str.encode("utf-8")
|
||||
auth_base64 = base64.b64encode(auth_bytes).decode("utf-8")
|
||||
|
||||
# ✅ URL de l'API WooCommerce pour les médias
|
||||
media_api_url = "https://lescreationsdemissbleue.local/wp-json/wp/v2/media"
|
||||
products_api_url = "https://lescreationsdemissbleue.local/wp-json/wc/v3/products"
|
||||
headers = {
|
||||
"Authorization": f"Basic {base64.b64encode(f'{wcapi.consumer_key}:{wcapi.consumer_secret}'.encode()).decode()}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
# API category
|
||||
|
||||
categories_api_url = "https://lescreationsdemissbleue.local/wp-json/wp/v2/product_cat"
|
||||
|
||||
def create_category(categories_api_url, headers, name, description, image_id=None, parent_id=None):
|
||||
"""Crée une catégorie WooCommerce (principale ou sous-catégorie)"""
|
||||
category_data = {
|
||||
"name": name,
|
||||
"description": description,
|
||||
"image" :
|
||||
{
|
||||
"id":image_id
|
||||
},
|
||||
"parent": parent_id if parent_id else 0,
|
||||
}
|
||||
|
||||
response = requests.post(categories_api_url, headers=headers, json=category_data)
|
||||
|
||||
if response.status_code == 201:
|
||||
category = response.json()
|
||||
print(f"✅ Catégorie '{name}' créée avec succès ! ID : {category['id']}")
|
||||
return category["id"]
|
||||
else:
|
||||
print(f"❌ Erreur lors de la création de '{name}' : {response.status_code} {response.text}")
|
||||
return None
|
||||
|
||||
# ✅ Exécuter la création automatique
|
||||
"""category_parent_id = create_category("Gamme prestige", "Catégorie principale pour organiser la gamme prestige")
|
||||
if category_parent_id:
|
||||
subcategory_id = create_category("Chopes", "Sous-catégorie de la gamme prestige", category_parent_id)
|
||||
"""
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# ✅ Récupérer les produits
|
||||
"""response = requests.get(products_api_url, headers=headers, params={"per_page": 100}, verify=False) # Limite à 100 produits
|
||||
|
||||
if response.status_code == 200:
|
||||
products = response.json()
|
||||
|
||||
# 📌 Extraire les ID et noms des produits ainsi que leurs catégories associées
|
||||
for product in products:
|
||||
product_id = product["id"]
|
||||
product_name = product["name"]
|
||||
categories = [cat["name"] for cat in product["categories"]] # Récupérer les noms des catégories
|
||||
|
||||
print(f"📌 Produit ID: {product_id} - Nom: {product_name} - Catégories: {', '.join(categories) if categories else 'Aucune'}")
|
||||
else:
|
||||
print(f"❌ Erreur : {response.status_code} {response.text}")"""
|
||||
|
||||
"""response_create_category = wcapi.post("products/categories/", category_data)
|
||||
if response_create_category.status_code == 201:
|
||||
#wcapi.put("products/categories/199", data).json()
|
||||
#wcapi.put("products/199", data)
|
||||
#pprint.pprint(response.json())
|
||||
#response = wcapi.put("products/199", data)
|
||||
category = response_create_category.json()
|
||||
category_id = category["id"]
|
||||
pprint.pprint(response_create_category.json())
|
||||
print(f"category_id = {category_id}")
|
||||
else:
|
||||
print("Erreur lors de la connexion :", response.text)"""
|
||||
|
||||
import pandas as pd
|
||||
import ezodf
|
||||
|
||||
# Charger le fichier ODS
|
||||
ezodf.config.set_table_expand_strategy('all')
|
||||
doc = ezodf.opendoc("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\infos_site.ods")
|
||||
|
||||
# Sélectionner la première feuille
|
||||
sheet = doc.sheets[0]
|
||||
|
||||
# Convertir la feuille en DataFrame
|
||||
data = []
|
||||
for row in sheet.rows():
|
||||
data.append([cell.value for cell in row])
|
||||
import json
|
||||
# Convertir en DataFrame Pandas
|
||||
df = pd.DataFrame(data)
|
||||
|
||||
# Vérifier que la première ligne contient bien les noms des colonnes
|
||||
df.columns = df.iloc[0] # Définit la première ligne comme noms des colonnes
|
||||
df = df[1:].reset_index(drop=True) # Supprime la première ligne et réindexe correctement
|
||||
df = df.dropna(how='all') # Supprime les lignes entièrement vides
|
||||
|
||||
# Convertir en JSON (clé = noms des colonnes)
|
||||
json_data = df.to_dict(orient="records")
|
||||
|
||||
# Afficher le JSON formaté
|
||||
#print(json.dumps(json_data, indent=4, ensure_ascii=False))
|
||||
for row in json_data:
|
||||
print(row['Photo'])
|
||||
#get_data = json.dumps(json_data, indent=4, ensure_ascii=False)
|
||||
|
||||
|
||||
436
api_old_code.py
436
api_old_code.py
@ -1,436 +0,0 @@
|
||||
from woocommerce import API
|
||||
import pandas as pd
|
||||
import ezodf
|
||||
import requests
|
||||
import pprint
|
||||
import base64
|
||||
import time
|
||||
import json
|
||||
|
||||
wcapi = API(
|
||||
url="https://lescreationsdemissbleue.local",
|
||||
consumer_key="ck_604e9b7b5d290cce72346efade6b31cb9a1ff28e",
|
||||
consumer_secret="cs_563974c7e59532c1ae1d0f8bbf61f0500d6bc768",
|
||||
wp_api=True,
|
||||
version="wc/v3",
|
||||
verify_ssl=False # Désactive la vérification SSL pour le développement
|
||||
)
|
||||
|
||||
class Authentification:
|
||||
# Identifiants WordPress (et non WooCommerce)
|
||||
wordpress_username = "admin_lcdm" # Remplace par ton username WordPress
|
||||
wordpress_application_password = "yTW8 Mc6J FUCN tPSq bnuJ 0Sdw" #"#8io_mb!55@Bis" # Généré dans WordPress > Utilisateurs
|
||||
|
||||
# Générer l'authentification Basic en base64
|
||||
auth_str = f"{wordpress_username}:{wordpress_application_password}"
|
||||
auth_bytes = auth_str.encode("utf-8")
|
||||
auth_base64 = base64.b64encode(auth_bytes).decode("utf-8")
|
||||
|
||||
ath = Authentification()
|
||||
|
||||
path_name = "C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_Claudine\\Photos_bougies_Claudine"
|
||||
|
||||
images_to_upload = [
|
||||
{'categories': [
|
||||
(f"{path_name}\\Bougies\\Chope\\chope-sapin-face.jpg", "chope-sapin-face.jpg", "Chope sapin", "Chope sapin de face", "Gamme prestige"),
|
||||
(f"{path_name}\\Bougies\\Chope\\chope-adoucissant-face.jpg", "chope-adoucissant-face.jpg", "Chope adoucissant", "Chope adoucissant de face", "Chopes"),
|
||||
]
|
||||
},
|
||||
{'products':[
|
||||
(f"{path_name}\\Bougies\\Chope\\chope-citron-meringue-face.jpg", "chope-citron-meringue-face-1.jpg", "Chope citron meringuée (1)", "Chope citron meringuée de face", "Chopes"),
|
||||
(f"{path_name}\\Bougies\\Chope\\chope-citron-meringue-haut.jpg", "chope-citron-meringue-haut-1.jpg", "Chope citron meringuée (2)", "Chope citron meringuée de haut", "Chopes"),
|
||||
(f"{path_name}\\Bougies\\Chope\\chope-citron-meringue-dos.jpg", "chope-citron-meringue-dos-1.jpg", "Chope citron meringuée (3)", "Chope citron meringuée de dos", "Chopes")
|
||||
]
|
||||
}
|
||||
]
|
||||
|
||||
category_parent_id = 0
|
||||
categories_to_create = [
|
||||
("Gamme prestige", "Catégorie principale pour organiser la gamme prestige", None),
|
||||
("Chopes", "Catégorie enfant de la gamme prestige", category_parent_id),
|
||||
]
|
||||
|
||||
#media_api_url = f"https://lescreationsdemissbleue.local/wp-json/wp/v2/media"
|
||||
|
||||
class ImageManager:
|
||||
|
||||
def __init__(self, images_to_upload, ath, url_website):
|
||||
self.images_to_upload = images_to_upload
|
||||
self.ath = ath
|
||||
self.media_api_url = f"{url_website}/wp-json/wp/v2/media"
|
||||
self.dict_image = {}
|
||||
self.headers = {
|
||||
"Authorization": f"Basic {self.ath.auth_base64}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
def update_data(self, title, alt, image_id):
|
||||
updata_data = {
|
||||
"title" : title,
|
||||
"alt_text": alt
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
f"{self.media_api_url}/{image_id}",
|
||||
headers=self.headers,
|
||||
json=updata_data,
|
||||
verify=False
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
return response.json()
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
|
||||
def upload_image(self, image_path, image_name, title, alt, category_name):
|
||||
with open(image_path, "rb") as image_file:
|
||||
response = requests.post(
|
||||
self.media_api_url,
|
||||
headers={
|
||||
"Authorization": f"Basic {self.ath.auth_base64}",
|
||||
"Content-Disposition": f"attachment; filename={image_name}"
|
||||
},
|
||||
files={"file": image_file},
|
||||
verify=False
|
||||
)
|
||||
|
||||
if response.status_code == 201:
|
||||
media_data = response.json()
|
||||
self.update_data(title, alt, media_data["id"])
|
||||
return {'category_name':category_name, 'id':media_data["id"], 'image_name':image_name, 'title':title} # Retourne l'ID de l'image
|
||||
else:
|
||||
return None
|
||||
|
||||
def update(self):
|
||||
uploaded_images_cat = []
|
||||
for image_path, image_name, title, alt, category_name in images_to_upload[0]['categories']:
|
||||
category_dict = self.upload_image(image_path, image_name, title, alt, category_name)
|
||||
uploaded_images_cat.append(category_dict)
|
||||
|
||||
uploaded_images_pro = []
|
||||
for image_path, image_name, title, alt, category_name in images_to_upload[1]['products']:
|
||||
image_dict = self.upload_image(image_path, image_name, title, alt, category_name)
|
||||
uploaded_images_pro.append(image_dict)
|
||||
|
||||
self.dict_image['category'] = uploaded_images_cat
|
||||
self.dict_image['product'] = uploaded_images_pro
|
||||
|
||||
return self.dict_image
|
||||
|
||||
def delete(self):
|
||||
pass
|
||||
|
||||
class CategoryManager:
|
||||
|
||||
def __init__(self, wcapi, ath, categories_to_create, url_website, uploaded_images):
|
||||
self.wcapi = wcapi
|
||||
self.ath = ath
|
||||
self.categories_to_create = categories_to_create
|
||||
self.categories_api_url = f"{url_website}/wp-json/wp/v2/product_cat"
|
||||
self.uploaded_images_cat = uploaded_images
|
||||
|
||||
self.media_api_url = f"{url_website}/wp-json/wp/v2/media"
|
||||
self.headers = {
|
||||
"Authorization": f"Basic {self.ath.auth_base64}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
def create_category(self, name, description, parent_id=None):
|
||||
category_data = {
|
||||
"name": name,
|
||||
"description": description,
|
||||
"parent": parent_id if parent_id else 0,
|
||||
}
|
||||
response = self.wcapi.post("products/categories/", category_data)
|
||||
if response.status_code == 201:
|
||||
category = response.json()
|
||||
return category
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_id_img_for_category(self, category):
|
||||
for cat_img in self.uploaded_images_cat:
|
||||
if category['name'] == cat_img['category_name']:
|
||||
image_id = {'id':cat_img['id']}
|
||||
#break
|
||||
return image_id
|
||||
|
||||
def update_data_img_id_for_category(self, img_id, cat_id):
|
||||
update_category_data = {
|
||||
"image" : img_id,
|
||||
}
|
||||
self.wcapi.put(f"products/categories/{cat_id}", update_category_data)
|
||||
|
||||
def update(self):
|
||||
for category in self.categories_to_create:
|
||||
name, description, parent_id = category
|
||||
if parent_id != None:
|
||||
parent_id = cat['id']
|
||||
cat = self.create_category(name, description, parent_id)
|
||||
img_id = self.get_id_img_for_category(cat)
|
||||
self.update_data_img_id_for_category(img_id,cat["id"])
|
||||
|
||||
def delete_category(self):
|
||||
response = self.wcapi.get(f"products/categories")
|
||||
for cat in response.json():
|
||||
print(f"cat_image = {cat['image']}")
|
||||
for category in self.categories_to_create:
|
||||
name, description, parent_id = category
|
||||
if cat['name'] == name:
|
||||
response = self.wcapi.delete(f"products/categories/{cat['id']}", params={"force": True})
|
||||
|
||||
def delete_img_category(self):
|
||||
for img_cat in self.uploaded_images_cat:
|
||||
print(f"img_cat['id'] = {img_cat['id']}")
|
||||
response = requests.delete(
|
||||
f"{self.media_api_url}/{img_cat['id']}",
|
||||
headers=self.headers,
|
||||
verify=False
|
||||
)
|
||||
|
||||
def delete_all_img_cat_by_name(self):
|
||||
response = requests.get(
|
||||
f"{self.media_api_url}?per_page=100",
|
||||
headers=self.headers,
|
||||
verify=False
|
||||
)
|
||||
images = response.json()
|
||||
for img in images:
|
||||
for path_image, name_image, title_image, text_alt, category_name in self.uploaded_images_cat:
|
||||
if img['title']['rendered'] == title_image:
|
||||
print(f"img_id = {img['id']}")
|
||||
print('iiii')
|
||||
response = requests.delete(
|
||||
f"{self.media_api_url}/{img['id']}?force=true",
|
||||
headers=self.headers,
|
||||
verify=False
|
||||
)
|
||||
|
||||
print(f"Status Code: {response.status_code}")
|
||||
pprint.pprint(response.json())
|
||||
|
||||
def delete(self):
|
||||
self.delete_category()
|
||||
#self.delete_img_category()
|
||||
self.delete_all_img_cat_by_name()
|
||||
|
||||
class ProductManager:
|
||||
def __init__(self, wcapi, ath, filename_ods, uploaded_images):
|
||||
self.wcapi = wcapi
|
||||
self.ath = ath
|
||||
self.uploaded_images_pro = uploaded_images
|
||||
self.filename_ods = filename_ods
|
||||
|
||||
self.media_api_url = f"{url_website}/wp-json/wp/v2/media"
|
||||
self.headers = {
|
||||
"Authorization": f"Basic {self.ath.auth_base64}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
def get_list_id_img_for_product(self, product):
|
||||
image_id = {}
|
||||
list_image_id_for_product = []
|
||||
list_images_by_doc = [img.strip().replace('"', '') for img in product['Photo'].split(",")]
|
||||
#pprint.pprint(self.uploaded_images_pro)
|
||||
for pro_img in self.uploaded_images_pro:
|
||||
for image in list_images_by_doc:
|
||||
#print(f"list_images_by_doc = {list_images_by_doc}")
|
||||
if image == pro_img['image_name']:
|
||||
image_id = {'id':pro_img['id']}
|
||||
list_image_id_for_product.append(image_id)
|
||||
#print(f"list_image_id_for_product = {list_image_id_for_product}")
|
||||
return list_image_id_for_product
|
||||
|
||||
def get_list_category_for_product(self, product):
|
||||
response = self.wcapi.get("products/categories")
|
||||
category_list_by_doc = [cat.strip().replace('"', '') for cat in product['Categorie'].split("/")]
|
||||
list_category_for_product = []
|
||||
for category in response.json():
|
||||
for cat in category_list_by_doc:
|
||||
#print(f"category['name'] = {category['name']}")
|
||||
#print(f"cat = {cat}")
|
||||
if category['name'] == cat:
|
||||
id_category = {'id':category['id']}
|
||||
list_category_for_product.append(id_category)
|
||||
return list_category_for_product
|
||||
|
||||
def update_data_list_cat_product(self, list_category_id, list_img_id, product_id):
|
||||
product_data = {
|
||||
'categories':list_category_id,
|
||||
'images':list_img_id,
|
||||
}
|
||||
print(f"product_id = {product_id}")
|
||||
self.wcapi.put(f"products/{product_id}", product_data)
|
||||
#self.wcapi.get(f"products/{product_id}")
|
||||
|
||||
def create_product(self, product):
|
||||
|
||||
product_data = {
|
||||
'name' : product['Nom'],
|
||||
'price': product['Prix'],
|
||||
'stock_quantity': product['Stock'],
|
||||
'description': product['Description'],
|
||||
'short_description': product['Courte_description'],
|
||||
}
|
||||
response = self.wcapi.post("products/", product_data)
|
||||
if response.status_code == 201:
|
||||
product = response.json()
|
||||
return product["id"]
|
||||
else:
|
||||
return None
|
||||
|
||||
def get_doc_ods(self):
|
||||
ezodf.config.set_table_expand_strategy('all')
|
||||
doc = ezodf.opendoc(self.filename_ods)
|
||||
sheet = doc.sheets[0]
|
||||
|
||||
# Convertir la feuille en DataFrame
|
||||
data = []
|
||||
for row in sheet.rows():
|
||||
data.append([cell.value for cell in row])
|
||||
|
||||
# Convertir en DataFrame Pandas
|
||||
df = pd.DataFrame(data)
|
||||
df.columns = df.iloc[0]
|
||||
df = df[1:].reset_index(drop=True)
|
||||
df = df.dropna(how='all')
|
||||
json_data = df.to_dict(orient="records")
|
||||
return json_data
|
||||
|
||||
def update(self):
|
||||
json_data = self.get_doc_ods()
|
||||
for product in json_data:
|
||||
product_id = self.create_product(product)
|
||||
list_category_id = self.get_list_category_for_product(product)
|
||||
list_img_id = self.get_list_id_img_for_product(product)
|
||||
self.update_data_list_cat_product(list_category_id, list_img_id, product_id)
|
||||
|
||||
def delete_product(self):
|
||||
json_data = self.get_doc_ods()
|
||||
for product in json_data:
|
||||
list_products = self.wcapi.get(f"products/")
|
||||
for pro in list_products.json():
|
||||
print(f"product['Nom'] = {product['Nom']}")
|
||||
print(f"pro['name'] = {pro['name']}")
|
||||
if product['Nom'] == pro['name']:
|
||||
self.wcapi.delete(f"products/{pro['id']}")
|
||||
|
||||
|
||||
def delete_img_product(self):
|
||||
list_products = self.wcapi.get(f"products/")
|
||||
for pro in list_products.json():
|
||||
#print(f"pro['name'] = {pro['name']}")
|
||||
for img_pro in self.uploaded_images_pro:
|
||||
#print(f"img_pro['title'] = {img_pro['title']}")
|
||||
if pro['name'] == img_pro['title']:
|
||||
#print(f"img_pro['id'] = {img_pro['id']}")
|
||||
#print(f"pro['id'] = {pro['id']}")
|
||||
response = requests.post(
|
||||
f"{self.media_api_url}/{img_pro['id']}",
|
||||
headers=self.headers,
|
||||
json={"force": True}, # 🔥 Forcer la suppressio
|
||||
verify=False
|
||||
)
|
||||
|
||||
|
||||
def delete_all_img_product_by_name(self):
|
||||
response = requests.get(
|
||||
f"{self.media_api_url}?per_page=100",
|
||||
headers=self.headers,
|
||||
verify=False
|
||||
)
|
||||
images = response.json()
|
||||
for img in images:
|
||||
for path_image, name_image, title_image, text_alt, category_name in self.uploaded_images_pro:
|
||||
if img['title']['rendered'] == title_image:
|
||||
print(f"img_id = {img['id']}")
|
||||
print('iiii')
|
||||
response = requests.delete(
|
||||
f"{self.media_api_url}/{img['id']}?force=true",
|
||||
headers=self.headers,
|
||||
verify=False
|
||||
)
|
||||
|
||||
print(f"Status Code: {response.status_code}")
|
||||
pprint.pprint(response.json())
|
||||
|
||||
def delete_all_img_product(self):
|
||||
response = requests.get(
|
||||
f"{self.media_api_url}?per_page=100",
|
||||
headers=self.headers,
|
||||
verify=False
|
||||
)
|
||||
images = response.json()
|
||||
for img in images:
|
||||
for img_pro in self.uploaded_images_pro:
|
||||
if img['title']['rendered'] == img_pro['title']:
|
||||
print('coucou')
|
||||
print(f"img_pro['id'] = {img_pro['id']}")
|
||||
print(f"img['id'] = {img['id']}")
|
||||
response = requests.delete(
|
||||
#f"{self.media_api_url}/{img['id']}?force=true"
|
||||
f"{self.media_api_url}/{img_pro['id']}?force=true",
|
||||
headers=self.headers,
|
||||
verify=False
|
||||
)
|
||||
print(f"Status Code: {response.status_code}")
|
||||
pprint.pprint(response.json())
|
||||
|
||||
|
||||
|
||||
def delete(self):
|
||||
#self.delete_product()
|
||||
#self.delete_img_product()
|
||||
#self.delete_all_img_product()
|
||||
self.delete_all_img_product_by_name()
|
||||
|
||||
url_website = "https://lescreationsdemissbleue.local"
|
||||
filename_ods = "C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\infos_site.ods"
|
||||
|
||||
image_manager = ImageManager(images_to_upload,ath,url_website)
|
||||
dict_image = image_manager.update()
|
||||
|
||||
#category_manager = CategoryManager(wcapi,ath,categories_to_create,url_website,dict_image['category'])
|
||||
#category_manager.update()
|
||||
#category_manager = CategoryManager(wcapi,ath,categories_to_create,url_website,images_to_upload[0]["categories"])
|
||||
#category_manager.delete()
|
||||
|
||||
product_manager = ProductManager(wcapi,ath,filename_ods,dict_image['product'])
|
||||
#product_manager.update()
|
||||
#product_manager = ProductManager(wcapi,ath,filename_ods, images_to_upload[1]["products"])
|
||||
product_manager.delete()
|
||||
|
||||
"""ALL_MEDIAS=[
|
||||
{ 'slug': None, 'title': None, 'alt_text': None }
|
||||
]
|
||||
|
||||
ALL_CATEGORIES=[
|
||||
{ 'name': None, 'parent_name': 'None', 'description': None, 'media_slug': None }
|
||||
]
|
||||
|
||||
ALL_PRODUCTS=[
|
||||
{ 'name': None, 'parent_name': 'None', 'description': None, 'media_slug_list': [] }
|
||||
]
|
||||
|
||||
api = WoocommerceApi(...)
|
||||
|
||||
media_manager = MediaManager(api=api)
|
||||
media_manager.upload(media_list=...)
|
||||
media_manager.find_id_by_slug(slug=...)
|
||||
media_manager.delete(slug=...)
|
||||
|
||||
category_manager = CategoryManager(api=api, medias=media_manager.get_all_as_slug_dict())
|
||||
category_manager.create(name, short_description, description, )
|
||||
|
||||
|
||||
product_manager = ProductManager(api=api, medias=media_manager.get_all())
|
||||
product_manager.create(product_list=...)
|
||||
|
||||
manager = WooCommerceManager(media_manager, category_manager, product_manager)
|
||||
|
||||
manager.delete_product(slug=...)
|
||||
|
||||
|
||||
"""
|
||||
@ -1,123 +0,0 @@
|
||||
import requests
|
||||
import base64
|
||||
import time
|
||||
from api import create_category
|
||||
|
||||
# ✅ Identifiants WordPress (et non WooCommerce)
|
||||
wordpress_username = "admin_lcdm" # Remplace par ton username WordPress
|
||||
wordpress_application_password = "yTW8 Mc6J FUCN tPSq bnuJ 0Sdw" #"#8io_mb!55@Bis" # Généré dans WordPress > Utilisateurs
|
||||
|
||||
# ✅ Générer l'authentification Basic en base64
|
||||
auth_str = f"{wordpress_username}:{wordpress_application_password}"
|
||||
auth_bytes = auth_str.encode("utf-8")
|
||||
auth_base64 = base64.b64encode(auth_bytes).decode("utf-8")
|
||||
|
||||
image_id = 675
|
||||
# ✅ URL de l'API WordPress pour téléverser une image
|
||||
media_api_url = f"https://lescreationsdemissbleue.local/wp-json/wp/v2/media/{image_id}"
|
||||
|
||||
# ✅ Fichier image à uploader
|
||||
image_path = "C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\pyramide_olfactive.png"
|
||||
image_name = "pyramide_olfactive.png"
|
||||
|
||||
images_to_upload = [
|
||||
("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_bougies_Claudine\\Bougies\\Chope\\chope-sapin-face.jpg", "chope-sapin-face.jpg"),
|
||||
("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_bougies_Claudine\\Bougies\\Chope\\chope-adoucissant-face.jpg", "chope-adoucissant-face.jpg")
|
||||
]
|
||||
|
||||
# ✅ Headers avec l'authentification correcte
|
||||
"""headers = {
|
||||
"Authorization": f"Basic {auth_base64}",
|
||||
"Content-Disposition": f"attachment; filename={image_name}"
|
||||
}"""
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Basic {auth_base64}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
updata_data = {
|
||||
"title" : "Pyramide olfactive test",
|
||||
"alt_text": "Pyramide olfactive test"
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
media_api_url,
|
||||
headers=headers,
|
||||
json=updata_data,
|
||||
verify=False # ⚠️ Désactiver la vérification SSL si problème de certificat
|
||||
)
|
||||
|
||||
# ✅ Lecture et envoi du fichier
|
||||
"""with open(image_path, "rb") as image_file:
|
||||
response = requests.post(
|
||||
media_api_url,
|
||||
headers=headers,
|
||||
files={"file": image_file},
|
||||
verify=False # ⚠️ Désactiver la vérification SSL si problème de certificat
|
||||
)"""
|
||||
|
||||
# ✅ Vérifier la réponse
|
||||
if response.status_code == 201:
|
||||
media_data = response.json()
|
||||
image_id = media_data["id"]
|
||||
image_url = media_data["source_url"]
|
||||
print(f"✅ Image téléversée avec succès ! ID : {image_id}, URL : {image_url}")
|
||||
else:
|
||||
print(f"❌ Erreur lors du téléversement de l'image : {response.status_code}")
|
||||
print(response.text) # 🔍 Afficher l'erreur détaillée
|
||||
|
||||
|
||||
"""def create_image(name, description, source):
|
||||
images_data = {
|
||||
"name": name,
|
||||
"description": description,
|
||||
"source": source
|
||||
}
|
||||
|
||||
response = requests.post(media_api_url, headers=headers, json=images_data)
|
||||
|
||||
if response.status_code == 201:
|
||||
category = response.json()
|
||||
print(f"✅ Catégorie '{name}' créée avec succès ! ID : {category['id']}")
|
||||
return category["id"]
|
||||
else:
|
||||
print(f"❌ Erreur lors de la création de '{name}' : {response.status_code} {response.text}")
|
||||
return None"""
|
||||
|
||||
categories_api_url = "https://lescreationsdemissbleue.local/wp-json/wp/v2/product_cat"
|
||||
|
||||
|
||||
def upload_image(image_path, image_name):
|
||||
with open(image_path, "rb") as image_file:
|
||||
response = requests.post(
|
||||
media_api_url,
|
||||
headers={
|
||||
"Authorization": f"Basic {auth_base64}",
|
||||
"Content-Disposition": f"attachment; filename={image_name}"
|
||||
},
|
||||
files={"file": image_file},
|
||||
verify=False
|
||||
)
|
||||
if response.status_code == 201:
|
||||
media_data = response.json()
|
||||
print(f"✅ Image téléversée : {media_data['source_url']}")
|
||||
category_parent_id = create_category("Gamme prestige", "Catégorie principale pour organiser la gamme prestige", media_data["id"])
|
||||
if category_parent_id:
|
||||
subcategory_id = create_category("Chopes", "Sous-catégorie de la gamme prestige", category_parent_id, media_data["id"])
|
||||
return media_data["id"] # Retourne l'ID de l'image
|
||||
else:
|
||||
print(f"❌ Erreur image : {response.status_code} {response.text}")
|
||||
return None
|
||||
|
||||
# ✅ Boucle sur les images et envoi
|
||||
uploaded_images = []
|
||||
for image_path, image_name in images_to_upload:
|
||||
image_id = upload_image(image_path, image_name)
|
||||
print('iciiiiiiiiiiiii')
|
||||
if image_id:
|
||||
uploaded_images.append(image_id)
|
||||
time.sleep(2) # ⏳ Pause pour éviter la surcharge du serveur
|
||||
|
||||
# ✅ Liste des images téléversées avec leur ID
|
||||
print(f"📌 Images téléversées : {uploaded_images}")
|
||||
1136
api_woocommerce.py
1136
api_woocommerce.py
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@ -1,376 +0,0 @@
|
||||
from woocommerce import API
|
||||
import pandas as pd
|
||||
import ezodf
|
||||
import requests
|
||||
import pprint
|
||||
import base64
|
||||
import time
|
||||
import json
|
||||
|
||||
wcapi = API(
|
||||
url="https://lescreationsdemissbleue.local",
|
||||
consumer_key="ck_604e9b7b5d290cce72346efade6b31cb9a1ff28e",
|
||||
consumer_secret="cs_563974c7e59532c1ae1d0f8bbf61f0500d6bc768",
|
||||
wp_api=True,
|
||||
version="wc/v3",
|
||||
verify_ssl=False # Désactive la vérification SSL pour le développement
|
||||
)
|
||||
|
||||
# ✅ Identifiants WordPress (et non WooCommerce)
|
||||
wordpress_username = "admin_lcdm" # Remplace par ton username WordPress
|
||||
wordpress_application_password = "yTW8 Mc6J FUCN tPSq bnuJ 0Sdw" #"#8io_mb!55@Bis" # Généré dans WordPress > Utilisateurs
|
||||
|
||||
# ✅ Générer l'authentification Basic en base64
|
||||
auth_str = f"{wordpress_username}:{wordpress_application_password}"
|
||||
auth_bytes = auth_str.encode("utf-8")
|
||||
auth_base64 = base64.b64encode(auth_bytes).decode("utf-8")
|
||||
|
||||
images_to_upload = [
|
||||
{'categories': [
|
||||
("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_Claudine\\Photos_bougies_Claudine\\Bougies\\Chope\\chope-sapin-face.jpg", "chope-sapin-face.jpg", "Chope sapin", "Chope sapin de face", "Gamme prestige"),
|
||||
("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_Claudine\\Photos_bougies_Claudine\\Bougies\\Chope\\chope-adoucissant-face.jpg", "chope-adoucissant-face.jpg", "Chope adoucissant", "Chope adoucissant de face", "Chopes"),
|
||||
]
|
||||
},
|
||||
{'images':[
|
||||
("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_Claudine\\Photos_bougies_Claudine\\Bougies\\Chope\\chope-citron-meringue-face.jpg", "chope-citron-meringue-face.jpg", "Chope citron meringuée (1)", "Chope citron meringuée de face", "Chopes"),
|
||||
("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_Claudine\\Photos_bougies_Claudine\\Bougies\\Chope\\chope-citron-meringue-haut.jpg", "chope-citron-meringue-haut.jpg", "Chope citron meringuée (2)", "Chope citron meringuée de haut", "Chopes"),
|
||||
("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\photos\\Photos_Claudine\\Photos_bougies_Claudine\\Bougies\\Chope\\chope-citron-meringue-dos.jpg", "chope-citron-meringue-dos.jpg", "Chope citron meringuée (3)", "Chope citron meringuée de dos", "Chopes")
|
||||
]
|
||||
}
|
||||
]
|
||||
"""updata_data = {
|
||||
"title" : "Pyramide olfactive test",
|
||||
"alt_text": "Pyramide olfactive test"
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
media_api_url,
|
||||
headers=headers,
|
||||
json=updata_data,
|
||||
verify=False # ⚠️ Désactiver la vérification SSL si problème de certificat
|
||||
)"""
|
||||
|
||||
|
||||
def update_data(title, alt, image_id):
|
||||
updata_data = {
|
||||
"title" : title,
|
||||
"alt_text": alt
|
||||
}
|
||||
headers = {
|
||||
"Authorization": f"Basic {auth_base64}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
f"{media_api_url}/{image_id}",
|
||||
headers=headers,
|
||||
json=updata_data,
|
||||
verify=False # ⚠️ Désactiver la vérification SSL si problème de certificat
|
||||
)
|
||||
# ✅ Vérifier la réponse
|
||||
if response.status_code == 200:
|
||||
print(f"✅ Métadonnées mises à jour pour l’image {image_id} : {title} | ALT : {alt}")
|
||||
return response.json() # Retourne les nouvelles données de l'image
|
||||
else:
|
||||
print(f"❌ Erreur mise à jour image : {response.status_code} {response.text}")
|
||||
return None
|
||||
|
||||
media_api_url = f"https://lescreationsdemissbleue.local/wp-json/wp/v2/media"
|
||||
|
||||
def upload_image(image_path, image_name, title, alt, category_name):
|
||||
with open(image_path, "rb") as image_file:
|
||||
response = requests.post(
|
||||
media_api_url,
|
||||
headers={
|
||||
"Authorization": f"Basic {auth_base64}",
|
||||
"Content-Disposition": f"attachment; filename={image_name}"
|
||||
},
|
||||
files={"file": image_file},
|
||||
verify=False
|
||||
)
|
||||
|
||||
if response.status_code == 201:
|
||||
media_data = response.json()
|
||||
update_data(title, alt, media_data["id"])
|
||||
return {'category_name':category_name, 'id':media_data["id"], 'image_name':image_name} # Retourne l'ID de l'image
|
||||
else:
|
||||
print(f"❌ Erreur image : {response.status_code} {response.text}")
|
||||
return None
|
||||
|
||||
categories_api_url = "https://lescreationsdemissbleue.local/wp-json/wp/v2/product_cat"
|
||||
category_parent_id = 0
|
||||
image_id= None
|
||||
categories_to_create = [
|
||||
("Gamme prestige", "Catégorie principale pour organiser la gamme prestige", None),
|
||||
("Chopes", "Catégorie enfant de la gamme prestige", category_parent_id),
|
||||
]
|
||||
|
||||
def create_category(name, description, parent_id=None):
|
||||
"""Crée une catégorie WooCommerce (principale ou sous-catégorie)"""
|
||||
category_data = {
|
||||
"name": name,
|
||||
"description": description,
|
||||
"parent": parent_id if parent_id else 0,
|
||||
#'images':image_id
|
||||
}
|
||||
response = wcapi.post("products/categories/", category_data)
|
||||
|
||||
print(f"response.status_code = {response.status_code}")
|
||||
print(f"Réponse API = {response.text}")
|
||||
if response.status_code == 201:
|
||||
category = response.json()
|
||||
#pprint.pprint(category)
|
||||
#return category["id"]
|
||||
return category
|
||||
else:
|
||||
return None
|
||||
|
||||
uploaded_images_cat = []
|
||||
for image_path, image_name, title, alt, category_name in images_to_upload[0]['categories']:
|
||||
category_dict = upload_image(image_path, image_name, title, alt, category_name)
|
||||
uploaded_images_cat.append(category_dict)
|
||||
|
||||
for image_path, image_name, title, alt, category_name in images_to_upload[1]['images']:
|
||||
upload_image(image_path, image_name, title, alt, category_name)
|
||||
|
||||
|
||||
def get_id_img_for_category(category):
|
||||
headers = {
|
||||
"Authorization": f"Basic {auth_base64}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
response = requests.get(
|
||||
media_api_url,
|
||||
headers=headers,
|
||||
verify=False # ⚠️ Désactiver la vérification SSL si problème de certificat
|
||||
)
|
||||
response_images = response.json()
|
||||
image_id = {}
|
||||
for img in response_images:
|
||||
for cat_img in uploaded_images_cat:
|
||||
print(f"cat_img['id'] = {cat_img['id']}")
|
||||
if category['name'] == cat_img['category_name']:
|
||||
image_id = {'id':cat_img['id']}
|
||||
break
|
||||
print(f"image_id = {image_id}")
|
||||
return image_id
|
||||
|
||||
|
||||
def update_data_img_id_for_category(img_id, cat_id):
|
||||
update_category_data = {
|
||||
"image" : img_id,
|
||||
}
|
||||
print(f"cat_id = {cat_id}")
|
||||
print(f"img_id = {img_id}")
|
||||
response = wcapi.put(f"products/categories/{cat_id}", update_category_data)
|
||||
"""def get_id_img_for_category(category):
|
||||
category_list_by_doc = [cat.strip().replace('"', '') for cat in product['Categorie'].split("/")]
|
||||
#list_images_by_doc = [img.strip().replace('"', '') for img in product['Photo'].split(",")]
|
||||
#print(f'category_list_by_doc = {category_list_by_doc}')
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Basic {auth_base64}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
response = requests.get(
|
||||
media_api_url,
|
||||
headers=headers,
|
||||
verify=False # ⚠️ Désactiver la vérification SSL si problème de certificat
|
||||
)
|
||||
|
||||
response_images = response.json()
|
||||
#print(f"response_images = {type(response_images)}")
|
||||
for img in response_images:
|
||||
#print(f"type_img = {type(img)}")
|
||||
for key, value in img.items():
|
||||
if key == 'source_url':
|
||||
#print(f"key= {key}, value = {value}")
|
||||
for image in list_images_by_doc:
|
||||
if category['image_name'] in value:
|
||||
img_id = category['id']
|
||||
#pprint.pprint(f'list_image_for_product = {list_image_for_product}')
|
||||
return img_id"""
|
||||
|
||||
for category in categories_to_create:
|
||||
name, description, parent_id = category
|
||||
if parent_id != None:
|
||||
parent_id = cat['id']
|
||||
#img_id = get_id_img_for_category(category)
|
||||
cat = create_category(name, description, parent_id)
|
||||
img_id = get_id_img_for_category(cat)
|
||||
update_data_img_id_for_category(img_id,cat["id"])
|
||||
|
||||
def get_list_id_img_for_product(product):
|
||||
list_images_by_doc = [img.strip().replace('"', '') for img in product['Photo'].split(",")]
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Basic {auth_base64}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
response = requests.get(
|
||||
media_api_url,
|
||||
headers=headers,
|
||||
verify=False # ⚠️ Désactiver la vérification SSL si problème de certificat
|
||||
)
|
||||
|
||||
list_image_for_product = []
|
||||
response_images = response.json()
|
||||
for img in response_images:
|
||||
for key, value in img.items():
|
||||
if key == 'source_url':
|
||||
for image in list_images_by_doc:
|
||||
if image in value:
|
||||
img_id_for_product = {'id':img['id'], 'value':value}
|
||||
list_image_for_product.append(img_id_for_product)
|
||||
break
|
||||
return list_image_for_product[::-1]
|
||||
|
||||
|
||||
def get_list_category_for_product(product):
|
||||
response = wcapi.get("products/categories")
|
||||
category_list_by_doc = [cat.strip().replace('"', '') for cat in product['Categorie'].split("/")]
|
||||
list_category_for_product = []
|
||||
for category in response.json():
|
||||
for cat in category_list_by_doc:
|
||||
if category['name'] == cat:
|
||||
id_category = {'id':category['id']}
|
||||
list_category_for_product.append(id_category)
|
||||
return list_category_for_product
|
||||
|
||||
def update_data_list_cat_product(list_category_id, list_img_id, product_id):
|
||||
product_data = {
|
||||
'categories':list_category_id,
|
||||
'images':list_img_id,
|
||||
}
|
||||
wcapi.put(f"products/{product_id}", product_data)
|
||||
response_product = wcapi.get(f"products/{product_id}")
|
||||
|
||||
def create_product(product):
|
||||
|
||||
product_data = {
|
||||
'name' : product['Nom'],
|
||||
'price': product['Prix'],
|
||||
'stock_quantity': product['Stock'],
|
||||
'description': product['Description'],
|
||||
#'images':list_id_image,
|
||||
'short_description':product['Courte_description'],
|
||||
#'categories':list_id_category
|
||||
}
|
||||
response = wcapi.post("products/", product_data)
|
||||
|
||||
print(f"response.status_code = {response.status_code}")
|
||||
print("Réponse API :", response.text)
|
||||
if response.status_code == 201:
|
||||
product = response.json()
|
||||
return product["id"]
|
||||
else:
|
||||
return None
|
||||
|
||||
ezodf.config.set_table_expand_strategy('all')
|
||||
doc = ezodf.opendoc("C:\\Users\\beren\\OneDrive\\Documents\\nextcloud\\beren\\site_missbleue\\infos_site.ods")
|
||||
|
||||
# Sélectionner la première feuille
|
||||
sheet = doc.sheets[0]
|
||||
|
||||
# Convertir la feuille en DataFrame
|
||||
data = []
|
||||
for row in sheet.rows():
|
||||
data.append([cell.value for cell in row])
|
||||
|
||||
# Convertir en DataFrame Pandas
|
||||
df = pd.DataFrame(data)
|
||||
df.columns = df.iloc[0]
|
||||
df = df[1:].reset_index(drop=True)
|
||||
df = df.dropna(how='all')
|
||||
json_data = df.to_dict(orient="records")
|
||||
#get_data = json.dumps(json_data, indent=4, ensure_ascii=False)
|
||||
for product in json_data:
|
||||
#list_img_id = get_list_id_img_for_product(product)
|
||||
product_id = create_product(product)
|
||||
list_category_id = get_list_category_for_product(product)
|
||||
list_img_id = get_list_id_img_for_product(product)
|
||||
update_data_list_cat_product(list_category_id, list_img_id, product_id)
|
||||
"""
|
||||
categories_to_create = [
|
||||
("Gamme prestige", "Catégorie principale pour organiser la gamme prestige", image_id, None),
|
||||
("Chope", "Catégorie enfant de la gamme prestige", image_id, category_parent_id),
|
||||
]
|
||||
|
||||
uploaded_images_cat = []
|
||||
for image_path, image_name, title, alt, category_name in images_to_upload[0]['categories']:
|
||||
image_name_id = upload_image(image_path, image_name, title, alt, category_name)
|
||||
if image_name_id:
|
||||
uploaded_images_cat.append(image_name_id)
|
||||
|
||||
uploaded_images = []
|
||||
for image_path, image_name, title, alt, category_name in images_to_upload[1]['images']:
|
||||
|
||||
print(f'image_name = {image_name}')
|
||||
image_name_id = upload_image(image_path, image_name, title, alt, category_name)
|
||||
if image_name_id:
|
||||
uploaded_images.append(image_name_id)
|
||||
print(f"uploaded_images = {uploaded_images}")
|
||||
|
||||
def create_category(name, description, image_id=None, parent_id=None):
|
||||
category_data = {
|
||||
"name": name,
|
||||
"description": description,
|
||||
"parent": parent_id if parent_id else 0,
|
||||
}
|
||||
if image_id:
|
||||
category_data['image'] = {'id':image_id}
|
||||
|
||||
|
||||
#response = requests.post(categories_api_url, headers=headers, json=category_data, verify=False)
|
||||
response = wcapi.post("products/categories/", category_data)
|
||||
|
||||
print(f"response.status_code = {response.status_code}")
|
||||
print(f"Réponse API = {response.text}")
|
||||
if response.status_code == 201:
|
||||
category = response.json()
|
||||
#pprint.pprint(category)
|
||||
#return category["id"]
|
||||
return {'category_name':category_name, 'id':category["id"]}
|
||||
else:
|
||||
return None
|
||||
|
||||
categories_list = []
|
||||
for category in categories_to_create:
|
||||
name, description, image_id, parent_id = category
|
||||
for image in uploaded_images_cat:
|
||||
if image['category_name'] == name:
|
||||
image_id = image['id']
|
||||
if parent_id != None:
|
||||
parent_id = cat['id']
|
||||
cat = create_category(name, description, image_id, parent_id)
|
||||
print(f"category = {category}")
|
||||
print(type(category))
|
||||
categories_list.append(cat)
|
||||
"""
|
||||
"""list_id_image = []
|
||||
pprint.pprint(uploaded_images)
|
||||
for image in uploaded_images:
|
||||
if image['image_name'] in image_list:
|
||||
image = {'id':image['id']}
|
||||
list_id_image.append(image)
|
||||
|
||||
list_id_category = []
|
||||
pprint.pprint(categories_list)
|
||||
pprint.pprint(category_list)
|
||||
print('______')
|
||||
for category in categories_list:
|
||||
print(f'categoryyyy = {category}')
|
||||
if category['category_name'] in category_list:
|
||||
print(f"category['id'] = {category['id']}")
|
||||
cat = {'id':category['id']}
|
||||
list_id_category.append(cat)
|
||||
print(f"list_id_category = {list_id_category}")
|
||||
|
||||
list_test = []
|
||||
test = {'id':3}
|
||||
list_test.append(test)
|
||||
print(f"list_test = {list_test}") """
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
|
Before Width: | Height: | Size: 177 KiB After Width: | Height: | Size: 177 KiB |
213665
woocommerce.log
213665
woocommerce.log
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user