Created
July 21, 2023 16:09
-
-
Save Hunter87ff/57ec9731dd86b7509544b996498b2c49 to your computer and use it in GitHub Desktop.
realtime flask server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- templates/index.html --> | |
<html> | |
<body> | |
<h1>Real-Time Website</h1> | |
<div id="data-container"></div> | |
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.1.3/socket.io.js"></script> | |
<script> | |
const socket = io.connect('http://' + document.domain + ':' + location.port); | |
// Event listener to handle incoming data from the server | |
socket.on('updatedData', (data) => { | |
// Handle the updated data and update your website's frontend | |
document.getElementById('data-container').innerText = data; | |
}); | |
// Function to send data to the server | |
function sendDataToServer() { | |
const dataToSend = 'Some updated data'; | |
socket.emit('update', dataToSend); | |
} | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app.py | |
from flask import Flask, render_template | |
from flask_socketio import SocketIO, emit | |
app = Flask(__name__) | |
app.config['SECRET_KEY'] = 'secret-key' | |
socketio = SocketIO(app) | |
@app.route('/') | |
def index(): | |
return render_template('index.html') | |
@socketio.on('connect') | |
def handle_connect(): | |
print('A user connected') | |
@socketio.on('disconnect') | |
def handle_disconnect(): | |
print('A user disconnected') | |
@socketio.on('update') | |
def handle_update(data): | |
# Process the incoming data from the frontend as needed | |
# In this example, we'll simply broadcast the received data to all clients | |
emit('updatedData', data, broadcast=True) | |
if __name__ == '__main__': | |
socketio.run(app, host='localhost', port=8765) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment