habulaj commited on
Commit
196b3df
·
verified ·
1 Parent(s): 7df9479

Create wordpress.py

Browse files
Files changed (1) hide show
  1. routers/wordpress.py +61 -0
routers/wordpress.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import httpx
3
+ from fastapi import APIRouter, HTTPException
4
+
5
+ router = APIRouter()
6
+
7
+ # 🔧 Configuração do WordPress
8
+ WP_URL = os.getenv("WP_URL") # ex: https://seusite.com/wp-json/wp/v2
9
+ WP_USER = os.getenv("WP_USER")
10
+ WP_PASS = os.getenv("WP_PASS") # senha de aplicativo ou basic auth
11
+
12
+ if not WP_URL or not WP_USER or not WP_PASS:
13
+ raise ValueError("❌ WP_URL, WP_USER ou WP_PASS não configurados!")
14
+
15
+ AUTH = (WP_USER, WP_PASS)
16
+
17
+ # 🚀 Criar post no WordPress
18
+ @router.post("/wordpress/post")
19
+ async def create_wordpress_post(title: str, content: str, image_url: str = None, status: str = "publish"):
20
+ async with httpx.AsyncClient(timeout=20.0) as client:
21
+ # Se houver imagem → baixar e enviar como mídia destacada
22
+ featured_media_id = None
23
+ if image_url:
24
+ try:
25
+ img_resp = await client.get(image_url, timeout=15.0)
26
+ if img_resp.status_code == 200:
27
+ filename = image_url.split("/")[-1].split("?")[0]
28
+ media_headers = {
29
+ "Content-Disposition": f"attachment; filename={filename}",
30
+ "Content-Type": img_resp.headers.get("content-type", "image/jpeg")
31
+ }
32
+ media_url = f"{WP_URL}/media"
33
+ upload = await client.post(
34
+ media_url,
35
+ auth=AUTH,
36
+ headers=media_headers,
37
+ content=img_resp.content
38
+ )
39
+ if upload.status_code in [200, 201]:
40
+ featured_media_id = upload.json().get("id")
41
+ else:
42
+ print("⚠️ Falha ao enviar imagem:", upload.text)
43
+ except Exception as e:
44
+ print("⚠️ Erro ao baixar/enviar imagem:", e)
45
+
46
+ # Criar o post
47
+ post_data = {
48
+ "title": title,
49
+ "content": content,
50
+ "status": status
51
+ }
52
+ if featured_media_id:
53
+ post_data["featured_media"] = featured_media_id
54
+
55
+ post_url = f"{WP_URL}/posts"
56
+ response = await client.post(post_url, auth=AUTH, json=post_data)
57
+
58
+ if response.status_code not in [200, 201]:
59
+ raise HTTPException(status_code=response.status_code, detail=response.text)
60
+
61
+ return response.json()