Loading repository data…
Loading repository data…
GustavoGarciaPereira / repository
WebSocket Notifications Demo – Um projeto educacional simples que demonstra como implementar notificações em tempo real usando WebSocket e FastAPI, com uma interface frontend estilizada em HTML, CSS e JavaScript. Ideal para quem quer aprender conceitos básicos de comunicação bidirecional e criar experiências interativas na web. 🚀🔔
A transparent discovery signal based on current public GitHub metadata.
This score does not audit code, security, maintainers, documentation quality, or suitability. Verify the repository and its current documentation before adoption.
Este repositório contém um exemplo educacional de como implementar notificações em tempo real utilizando WebSocket e FastAPI, com uma interface frontend estilizada em HTML e CSS. O projeto é voltado para quem deseja aprender conceitos básicos de comunicação em tempo real e WebSocket.
⚠️ Aviso: Este projeto é apenas um experimento educacional e não deve ser utilizado em ambientes de produção.
O projeto consiste em:
Certifique-se de ter o seguinte instalado:
Instale as dependências:
pip install fastapi uvicorn
pip install websockets
Crie o arquivo do servidor (main.py):
from fastapi import FastAPI, WebSocket
from fastapi.responses import HTMLResponse
app = FastAPI()
@app.get("/")
async def get():
with open("index.html", "r") as f:
return HTMLResponse(content=f.read(), status_code=200)
@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
await websocket.accept()
while True:
data = await websocket.receive_text()
await websocket.send_text(f"Mensagem recebida: {data}")
Execute o servidor:
uvicorn main:app --reload
Crie o arquivo index.html com o seguinte conteúdo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Push Notifications com WebSocket</title>
<style>
body {
background-color: #f4f4f4;
font-family: 'Arial', sans-serif;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
margin: 0;
}
h1 {
text-align: center;
font-size: 2rem;
color: #333;
}
#notifications {
max-width: 400px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
padding: 20px;
max-height: 500px;
overflow-y: auto;
}
.notification {
background-color: #e0f7fa;
border-left: 5px solid #00838f;
padding: 10px;
margin-bottom: 10px;
border-radius: 4px;
display: flex;
justify-content: space-between;
align-items: center;
animation: fadeIn 0.5s;
}
.close-btn {
background-color: transparent;
border: none;
color: #00838f;
font-size: 1.2rem;
cursor: pointer;
margin-left: 10px;
}
.close-btn:hover {
color: #005662;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
@keyframes fadeOut {
from { opacity: 1; transform: translateY(0); }
to { opacity: 0; transform: translateY(10px); }
}
</style>
</head>
<body>
<div>
<h1>Notificações em Tempo Real</h1>
<div id="notifications"></div>
</div>
<script>
const notificationsDiv = document.getElementById('notifications');
const ws = new WebSocket("ws://localhost:8000/ws");
ws.onmessage = function (event) {
const notification = document.createElement('div');
notification.classList.add('notification');
const message = document.createElement('p');
message.textContent = `🔔 ${event.data}`;
const closeButton = document.createElement('button');
closeButton.classList.add('close-btn');
closeButton.innerHTML = '×';
closeButton.onclick = () => {
notification.style.animation = 'fadeOut 0.5s';
setTimeout(() => notification.remove(), 500);
};
notification.appendChild(message);
notification.appendChild(closeButton);
notificationsDiv.appendChild(notification);
notificationsDiv.scrollTop = notificationsDiv.scrollHeight;
};
ws.onopen = () => console.log("Conectado ao WebSocket");
ws.onclose = () => console.log("Desconectado do WebSocket");
</script>
</body>
</html>
Inicie o servidor FastAPI:
uvicorn main:app --reload
Acesse o frontend em http://localhost:8000.
Abra o console do navegador (F12) e envie mensagens para o WebSocket para ver as notificações em tempo real.
Para enviar as notificações faça assim usando o curl:
curl -X 'POST' \
'http://127.0.0.1:8000/send-notification/?message=oi notificacao' \
-H 'accept: application/json' \
-d ''
Divirta-se aprendendo e experimentando com notificações em tempo real! 🎉