Skip to content
Snippets Groups Projects

Issue #2: UPDATE Inserting a route to 'who we are'

Merged esrsc23 requested to merge issue-2/adicionando-rota-quem-somos into main
1 file
+ 62
51
Compare changes
  • Side-by-side
  • Inline
+ 62
51
# Importando bibliotecas
# Flask = Criação aplicação/serviço Web
# Request permite acessar as requisições
from flask import Flask, request
import os
app = Flask(__name__)
# Diretório onde os arquivos Markdown serão salvos
DIR = os.path.join(os.getcwd(), '../cms-c3sl/themes/c3sl/exampleSite/content/noticia')
# Diretórios onde os arquivos Markdown serão salvos
DIR_O_C3SL = os.path.join(os.getcwd(), '../cms-c3sl/themes/c3sl/exampleSite/content')
DIR_POSTS = os.path.join(os.getcwd(), '../cms-c3sl/themes/c3sl/exampleSite/content/noticia')
def create_or_update_post(post_id, data, event):
def create_or_update_post(post_id, data, event, content_type):
if not data:
return
# Armazena todos os atributos do JSON usando a própria variável Data
attributes = data.get('entry', {})
content = attributes.get('Descricao', '')
published_at = attributes.get('Data', '')
title = attributes.get('Titulo', '')
author = attributes.get('Autor', '')
summary = attributes.get('Sumario', '')
# Acessa a URL da imagem da imagem da lista
images = attributes.get('Imagem', [])
if images and isinstance(images, list):
image_url = images[0].get('url', '')
else:
image_url = ''
# Cria o nome do arquivo conforme o ID da notícia
file_name = f"{post_id}.md"
file_path = os.path.join(DIR, file_name)
if content_type == 'o-c3sl':
attributes = data.get('entry', {})
title = attributes.get('Titulo', '')
content = attributes.get('Descricao', '')
# Adiciona a linha "Edited: true" caso o evento seja de atualização da notícia
edited_line = 'Edited: true\n' if event == 'entry.update' else ''
# Nome fixo para single type
file_name = "quem-somos.md"
file_path = os.path.join(DIR_O_C3SL, file_name)
# Escreve os dados no formato Markdown na variável content_markdown
content_markdown = f"""---
content_markdown = f"""---
title: "{title}"
layout: 'legal'
---
{content}
"""
else:
attributes = data.get('entry', {})
content = attributes.get('Descricao', '')
published_at = attributes.get('Data', '')
title = attributes.get('Titulo', '')
author = attributes.get('Autor', '')
summary = attributes.get('Sumario', '')
images = attributes.get('Imagem', [])
if images and isinstance(images, list):
image_url = images[0].get('url', '')
else:
image_url = ''
file_name = f"{post_id}.md"
file_path = os.path.join(DIR_POSTS, file_name)
edited_line = 'Edited: true\n' if event == 'entry.update' else ''
content_markdown = f"""---
title: "{title}"
date: "{published_at}"
author: "{author}"
@@ -49,41 +57,44 @@ summary: "{summary}"
{content}
"""
# Escreve o arquivo no caminho solicitado
with open(file_path, 'w', encoding='utf8') as file:
file.write(content_markdown)
try:
with open(file_path, 'w', encoding='utf8') as file:
file.write(content_markdown)
#print(f"Conteúdo do Markdown criado/atualizado para o post ID {post_id}:\n{content_markdown}\n")
#print(f"Post '{title}' salvo como {file_path}")
except Exception as e:
print(f"Erro ao escrever o arquivo: {e}")
print(f"Conteúdo do Markdown criado/atualizado para o post ID {post_id}:\n{content_markdown}\n")
print(f"Post '{title}' salvo como {file_path}")
def delete_post(post_id, content_type):
if content_type == 'post':
file_name = f"{post_id}.md"
file_path = os.path.join(DIR_POSTS, file_name)
# Função responsável por excluir o post quando a requisição é do tipo delete ou unpublish
def delete_post(post_id):
file_name = f"{post_id}.md"
file_path = os.path.join(DIR, file_name)
if os.path.exists(file_path):
os.remove(file_path)
#print(f"Post com ID {post_id} deletado")
else:
print(f"Arquivo com ID {post_id} não encontrado para exclusão")
if os.path.exists(file_path):
os.remove(file_path)
print(f"Post com ID {post_id} deletado")
else:
print(f"Arquivo com ID {post_id} não encontrado para exclusão")
@app.route('/run-script', methods=['POST'])
def run_script():
# Recebe o JSON enviado pelo webhooks do Strapi
data = request.json
# Armazena o ID do post e também o tipo de evento (update, create ou delete...)
#print("Dados recebidos:", data)
post_id = data.get('entry', {}).get('id')
event = data.get('event') # Extraindo tipo do evento
print(f"Evento: {event}, ID: {post_id}")
event = data.get('event')
content_type = data.get('model', '') # Obtém o tipo de conteúdo do Strapi
print(f"Evento: {event}, ID: {post_id}, Tipo: {content_type}")
if not post_id:
return "ID not found in JSON", 400
if event in ['entry.update','entry.publish']:
create_or_update_post(post_id, data, event)
if event in ['entry.update', 'entry.publish']:
create_or_update_post(post_id, data, event, content_type)
elif event in ['entry.delete', 'entry.unpublish']:
delete_post(post_id)
delete_post(post_id, content_type)
else:
return "Evento não reconhecido", 400
Loading