I am working with Flask Socketio. My code right now console logs every time a user opens a page. However when I open the page in a new tab/window the console of the original user in not updated. Below is the code, have a look at it
let socket = io.connect("http://127.0.0.1:5000/")
socket.on("connect",() => {
socket.emit("my custom event",{text:"I have joined"})
})
socket.on("my response",function(msg) {
console.log(msg)
})
And here is the python code for flask
from flask import Flask, render_template, request
import requests
from flask_socketio import SocketIO, emit, send
app = Flask(__name__)
app.config["SECRET_KEY"] = "hope"
socketio = SocketIO(app)
#app.route('/')
def hello_world():
return render_template("index.html")
#app.route('/1')
def random_route():
return render_template("index2.html")
#socketio.on('message')
def message(data):
print(data)
#socketio.on('my custom event')
def handle_custom_event(data):
emit("my response", data)
if __name__ == "__main__":
socketio.run(app, debug=True)
The default for the emit function is to address the event only to the sender. If you want to address all your connected clients, you have to indicate so with the broadcast option:
#socketio.on('my custom event')
def handle_custom_event(data):
emit("my response", data, broadcast=True)
Related
from flask import Flask, render_template, request
import random
import datetime
app = Flask(__name__)
# List to store the submitted URLs
urls = []
#app.route('/')
def index():
return render_template('index.html')
#app.route('/submit', methods=['POST'])
def submit():
url = request.form['url']
# Add the URL to the list and return a success message
urls.append(url)
return "URL submitted successfully!"
#app.route('/stream')
def stream():
# Select a random URL from the last 20 days
now = datetime.datetime.now()
twenty_days_ago = now - datetime.timedelta(days=20)
recent_urls = [url for url in urls if url.submission_time > twenty_days_ago]
current_song_url = random.choice(recent_urls)
return render_template('stream.html', url=current_song_url)
if __name__ == '__main__':
app.run(debug=True)
I want to use this Code for my XAMPP Website (Html/php mostly used) but it only shows the code. So I watched some tutorials with config stuff and all that but then there is an internal server error. What should I do?
I tried to config Apache (httpd.conf) and installed everything (Python, Flask etc.)
I am currently trying to get a small server running on my RaspberryPi and accessing it from my PC within the LAN.
I get the following error when accessing the Raspberry, where the index.html is displayed to me just fine. Apparently it seems there are problems with my "resetList" endpoint.
I also tried the solution Solve Cross Origin Resource Sharing with Flask but it did not work for me. Thank you in advance.
I have the following Python code:
gevent.monkey.patch_all()
from flask import Flask, render_template
from flask_socketio import SocketIO
import dbfunctions as db
import json
from flask_cors import CORS
app = Flask(__name__, template_folder='./build', static_folder='./build/static')
CORS(app)
socket_io = SocketIO(app)
#app.route('/', methods=['GET', 'POST', 'PUT'])
def index():
return render_template('index.html')
# receiving messages
#socket_io.on('resetList')
def reset_list():
database = r"data.db"
conn = db.create_connection(database)
with conn:
data = db.get_data_without_initial(conn)
fields = ["id", "name", "profit", "sum", "high", "maxProfit", "last_update"]
json_list = []
for i in range(len(data)):
item_to_add = {fields[j]: data[i][j] for j in range(len(fields))}
json_list.append(item_to_add)
json.dumps(json_list)
socket_io.emit('receivedData', json_list)
if __name__ == '__main__':
socket_io.run(app, host='0.0.0.0', port=5000, debug=True)
i found a solution, the problem was not my python code it was my java code :/
a simple add of " transports: ["polling"] " solve the problem
import io from "socket.io-client";
let endPoint = "http://localhost:5000";
let socket = io.connect(`${endPoint}`, { transports: ["polling"] });
function receiveData(cb) {
socket.on("receivedData", (resp) => cb(resp));
}
export { receiveData };
I'm trying to learn Flask-SocketIO, Now i'm trying to do simple chat, but no one receives messages except the user in browser. Python/Flask code:
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = '?-.'
socketio = SocketIO(app)
#socketio.on('joined')
def handle_message(who):
emit('back', who)
#app.route("/")
def main_page():
return render_template("index.html")
if __name__ == '__main__':
socketio.run(app)
and Javascript:
var socket = io.connect('http://' + document.domain + ':' + location.port);
$('#mybut').on("click", function(){
socket.emit('joined', {who:'someone'});
});
socket.on('back', function(data) {
console.log(data['who'] + ' joined.')
});
You need to set the broadcast parameter in this case. Check the Flask-SocketIO docs on broadcasting.
I.e. change your handler to the following:
#socketio.on('joined')
def handle_message(who):
emit('back', who, broadcast=True)
The following view only generate output during the execution on Firefox.
On Chrome the request flush the entire response once, when the while ends, at the end.
What are making the it don't work on Chrome?
#processes.route('/read_buffer/<int:pid>')
def read_buffer(pid):
def generate():
sent = 0
while not settings.buffers[pid]['finished']:
for i, row in enumerate(settings.buffers[pid]['lines'][sent:]):
sent += 1
yield row
gevent.sleep(0.5)
return flask.Response(
response=generate(),
status=200,
mimetype="text/plain"
)
App config:
from flask_cors import CORS
from flask_socketio import SocketIO
app = flask.Flask(__name__)
app.config['DEBUG'] = False
app.register_blueprint(processes.processes, url_prefix='/processes')
CORS(app)
socketio = SocketIO(app, async_mode='gevent')
socketio.run(
app=app,
host=_config.get('server', 'host', fallback='0.0.0.0'),
port=_config.getint('server', 'port', fallback=5000),
use_reloader=False
)
I'm using the SocketIO because I'm using it in other places.
seems like a known bug in Chrome:
https://bugs.chromium.org/p/chromium/issues/detail?id=156023
import os
from flask import Flask
from flask import request
from flask import url_for
from flask import render_template
from twilio.rest import TwilioRestClient
from twilio import twiml
Declare and configure application
app = Flask(__name__, static_url_path='/static')
ACCOUNT_SID = "AACxxxxx"
AUTH_TOKEN = "xxxxxx"
client = TwilioRestClient(ACCOUNT_SID, AUTH_TOKEN)
Configure this number to a toll-free Twilio number to accept incoming calls.
#app.route('/caller', methods=['GET', 'POST'])
def caller():
response = twiml.Response()
response.say("Thank you for calling" \
"Please hold.")
response.enqueue("Queue Demo", waitUrl='/wait')
return str(response)
Configure waiting room to notify user of current position in the queue and
play the sweet, soothing sounds of Twilio's coffeeshop collection.
#app.route('/wait', methods=['GET', 'POST'])
def wait():
response = twiml.Response()
twilio_client.sms.messages.create(
to="+44xxxxxxxxxx",
from_="+44xxxxxxxxxx",
body="Hey Jenny! Good luck on the bar exam!",
)
response.say("You are number %s in line." % request.form['QueuePosition'])
response.play("https://s3-us-west-2.amazonaws.com/" \
"twilio/music1.mp3")
response.redirect('/wait')
return str(response)
Connect to support queue - assign to Twilio number for agent to call.
#app.route('/agent', methods=['GET', 'POST'])
def agent():
response = twiml.Response()
with response.dial() as dial:
dial.queue("Queue Demo")
return str(response)
If PORT not specified by environment, assume development config.
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
if port == 5000:
app.debug = False
app.run(host='0.0.0.0', port=port)
Why does it not send the sms?
Ok I resolved it, so if you are using python on twilio, this is the code to have your phone system that answers the call, puts the caller on hold playing music and then sends you an sms then you can call the number to help the caller.
Here it is:
import os
from flask import Flask
from flask import request
from flask import url_for
from flask import render_template
from twilio.rest import TwilioRestClient
from twilio import twiml
Declare and configure application
app = Flask(__name__, static_url_path='/static')
Configure this number to accept incoming calls.
#app.route('/caller', methods=['GET', 'POST'])
def caller():
response = twiml.Response()
response.say("Thank you for calling " \
"Please hold.")
response.enqueue("Queue Demo", waitUrl='/wait')
return str(response)
Configure the waiting room to notify the user of their current position in the queue and play the holding music or marketing message.
#app.route('/wait', methods=['GET', 'POST'])
def wait():
response = twiml.Response()
response.say("You are number %s in line." % request.form['QueuePosition'])
response.play("https://s3-us-west-2.amazonaws.com/" \
"triptorigatwilio/eventpremrigaholdmusic1.mp3")
response.redirect('/wait')
Notify agent of call via SMS
client = TwilioRestClient("your account sid...AC...", "your account auth token...xxxx")
client.sms.messages.create(
to="put number to send sms here",
from_="put the twilio number to send sms from here",
body="A caller is in the queue. Call now to help them.",
)
return str(response)
Connect to support queue - assign to Twilio number for agent to call.
#app.route('/agent', methods=['GET', 'POST'])
def agent():
response = twiml.Response()
with response.dial() as dial:
dial.queue("Queue Demo")
return str(response)
If PORT not specified by environment, assume development config.
if __name__ == '__main__':
port = int(os.environ.get("PORT", 5000))
if port == 5000:
app.debug = True
app.run(host='0.0.0.0', port=port)
Don't forget to configure your active numbers in twilio. The number the caller calls should point to /caller and the number for the agent calls should point to /agent. Good luck...