Skip to content
Snippets Groups Projects
Commit b74c9339 authored by Richard Fernando Heise Ferreira's avatar Richard Fernando Heise Ferreira
Browse files

Merge branch 'issue-2/adicionando-rota-quem-somos' into 'main'

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

See merge request !2
parents 2ecc1249 ebef491c
No related branches found
No related tags found
1 merge request!2Issue #2: UPDATE Inserting a route to 'who we are'
# Importando bibliotecas
# Flask = Criação aplicação/serviço Web
# Request permite acessar as requisições
from flask import Flask, request from flask import Flask, request
import os import os
app = Flask(__name__) app = Flask(__name__)
# Diretório onde os arquivos Markdown serão salvos # Diretórios onde os arquivos Markdown serão salvos
DIR = os.path.join(os.getcwd(), '../cms-c3sl/themes/c3sl/exampleSite/content/noticia') 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, content_type):
def create_or_update_post(post_id, data, event):
if not data: if not data:
return return
# Armazena todos os atributos do JSON usando a própria variável Data if content_type == 'o-c3sl':
attributes = data.get('entry', {})
title = attributes.get('Titulo', '')
content = attributes.get('Descricao', '')
# Nome fixo para single type
file_name = "quem-somos.md"
file_path = os.path.join(DIR_O_C3SL, file_name)
content_markdown = f"""---
title: "{title}"
layout: 'legal'
---
{content}
"""
else:
attributes = data.get('entry', {}) attributes = data.get('entry', {})
content = attributes.get('Descricao', '') content = attributes.get('Descricao', '')
published_at = attributes.get('Data', '') published_at = attributes.get('Data', '')
...@@ -22,21 +34,17 @@ def create_or_update_post(post_id, data, event): ...@@ -22,21 +34,17 @@ def create_or_update_post(post_id, data, event):
author = attributes.get('Autor', '') author = attributes.get('Autor', '')
summary = attributes.get('Sumario', '') summary = attributes.get('Sumario', '')
# Acessa a URL da imagem da imagem da lista
images = attributes.get('Imagem', []) images = attributes.get('Imagem', [])
if images and isinstance(images, list): if images and isinstance(images, list):
image_url = images[0].get('url', '') image_url = images[0].get('url', '')
else: else:
image_url = '' image_url = ''
# Cria o nome do arquivo conforme o ID da notícia
file_name = f"{post_id}.md" file_name = f"{post_id}.md"
file_path = os.path.join(DIR, file_name) file_path = os.path.join(DIR_POSTS, file_name)
# 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 '' edited_line = 'Edited: true\n' if event == 'entry.update' else ''
# Escreve os dados no formato Markdown na variável content_markdown
content_markdown = f"""--- content_markdown = f"""---
title: "{title}" title: "{title}"
date: "{published_at}" date: "{published_at}"
...@@ -49,41 +57,44 @@ summary: "{summary}" ...@@ -49,41 +57,44 @@ summary: "{summary}"
{content} {content}
""" """
# Escreve o arquivo no caminho solicitado try:
with open(file_path, 'w', encoding='utf8') as file: with open(file_path, 'w', encoding='utf8') as file:
file.write(content_markdown) 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") def delete_post(post_id, content_type):
print(f"Post '{title}' salvo como {file_path}") if content_type == 'post':
# 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_name = f"{post_id}.md"
file_path = os.path.join(DIR, file_name) file_path = os.path.join(DIR_POSTS, file_name)
if os.path.exists(file_path): if os.path.exists(file_path):
os.remove(file_path) os.remove(file_path)
print(f"Post com ID {post_id} deletado") #print(f"Post com ID {post_id} deletado")
else: else:
print(f"Arquivo com ID {post_id} não encontrado para exclusão") print(f"Arquivo com ID {post_id} não encontrado para exclusão")
@app.route('/run-script', methods=['POST']) @app.route('/run-script', methods=['POST'])
def run_script(): def run_script():
# Recebe o JSON enviado pelo webhooks do Strapi
data = request.json data = request.json
#print("Dados recebidos:", data)
# Armazena o ID do post e também o tipo de evento (update, create ou delete...)
post_id = data.get('entry', {}).get('id') post_id = data.get('entry', {}).get('id')
event = data.get('event') # Extraindo tipo do evento event = data.get('event')
print(f"Evento: {event}, ID: {post_id}") 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: if not post_id:
return "ID not found in JSON", 400 return "ID not found in JSON", 400
if event in ['entry.update', 'entry.publish']: if event in ['entry.update', 'entry.publish']:
create_or_update_post(post_id, data, event) create_or_update_post(post_id, data, event, content_type)
elif event in ['entry.delete', 'entry.unpublish']: elif event in ['entry.delete', 'entry.unpublish']:
delete_post(post_id) delete_post(post_id, content_type)
else: else:
return "Evento não reconhecido", 400 return "Evento não reconhecido", 400
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment