Comments (7)
When you want to emit from a regular route you have to use socketio.emit()
, only socket handlers have the socketio context necessary to call the plain emit()
.
from flask-socketio.
@NotLeet If you are working with Flask, then you should, in general, use emit()
, which is context-aware, so it works well in a Flask event handler. If you want to emit from a background thread, you can copy the request context and still use emit()
.
The socketio.emit()
method gives you direct access to the Socket.IO engine, without the Flask wrapper. You may want to use this function, I guess, but you don't really need to. You make it sound like these two emit options are at the same level but they are not. The emit()
function is Flask specific, socketio.emit()
is not, and in fact, emit()
is implemented by calling the lower level socketio.emit()
.
So what do you think the documentation should say? I would rather you always use emit()
, there is no use case where emit()
wouldn't work, as long as you have a Flask request context.
from flask-socketio.
@linuxson27 the emit
function tries to send the event back to the sender of an originating event. Since there is no originating event in this case, you have to indicate who the addressee is.
Are you storing the sid
value for your clients? You need to add room=sid
to the call, with the sid
for the client you want to address. You can also pass the name of a room you created, or if you prefer, pass broadcast=True
to send the event to all clients.
from flask-socketio.
Hey Miguel, I love your work, but as a first time user of this library this issue did catch me.
It's mentioned briefly in your documentation, here,
"Note that socketio.send() and socketio.emit() are not the same functions as the context-aware send() and emit()."
and obviously I found this answer in Google, but it may be worth it to make a small note in the flask-socketio documentation highlighting this potential stumbling block.
Anyway, I'm looking forward to your new flask mega-tutorial, and thanks again for all you do.
from flask-socketio.
Hi, been struggling with whether to use socketio.emit() and emit() myself...have a Flask application where I am just trying to emit a signal server side to the client to confirm that a MongoDB insert() method has indeed fired and completed. After hours of pulling my hair out, I finally came across this thread, and noticed the use of just emit(), which I have implemented (see below):
@app.route('/', methods=['GET', 'POST'])
def home():
register_form = RegisterForm()
if register_form.validate_on_submit():
users = mongo.db.users
users.insert({
'user': register_form.name.data,
'password': register_form.password.data,
'role': register_form.role.data})
def ack():
print('Message was received')
emit('name_added', 'User has been added', namespace='/', callback=ack)
return render_template('index.html', register_form=register_form)
Still finding my feet with Flask, so pardon any bad coding on my behalf. This emit signal is however returning an error: AttributeError: 'Request' object has no attribute 'sid'
How do I fix this?
PS: This is my code client side...
<body>
<div class="container">
<div class="d-flex justify-content-center mt-5">
<div class="w-25 text-center mt-5">
<form method="POST" action="{{url_for('home')}}">
{{register_form.csrf_token}}
{{register_form.name(class_='form-control font-weight-light mb-4', type='text', placeholder='username')}}
{{register_form.password(class_='form-control font-weight-light mb-4', type='password', placeholder='password')}}
{{register_form.role(class_='custom-select mt-2 mb-4')}}
<button type="submit" id="sendButton" class="btn btn-raised btn-info mt-4 w-100 rounded-0">Send</button>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function() {
var socket = io.connect('http://127.0.0.1:5000');
socket.on('name_added', function(data) {
console.log(data)
})
});
</script>
</body>
from flask-socketio.
Hi Miguel,
I am trying to call socketio.emit function but it did not work.
here is the code:
from app import socketio
from flask_socketio import SocketIO, emit, join_room, leave_room, \
close_room, rooms, disconnect
def msg_process(msg, tstamp):
socketio.emit('start_your_task', {'message': [worker.AMT_worker_id]})
@main.route('/api/from', methods = ['GET', 'POST', 'PUT'])
msg_process(js['Message'], js['Timestamp'])
what I am doing wrong? I did not share the complete code
from flask-socketio.
@tahir80 what do you mean by "it didn't work"? There isn't anything obviously wrong in the code that you are showing me, the problem must be somewhere else.
from flask-socketio.
Related Issues (20)
- ConnectionRefusedError exceptions in connect handler are ignored
- I'm getting error when using self signed SSL HOT 2
- Flask socketio test_client method to test received ConnectionRefusedError messages HOT 5
- Flask-SocketIO Admin UI HOT 4
- "ValueError: Invalid empty packet received" when launched via gunicorn/gevent HOT 2
- TypeError: <engineio.packet.Packet object at 0xabec08e0> is not a byte HOT 1
- Add support for redis sentinel cluster HOT 2
- Test cookie handling API changed in Werkzeug 2.3 HOT 1
- Unable to connect to namespaces other than the main namespace HOT 1
- Cannot start multiple threads HOT 1
- Support for once to listen for an event only 1 time (Like official socket.io server has) HOT 1
- Error when using gevent with allow_unsafe_werkzeug HOT 2
- Option to redirect http to https instead of raising errors HOT 1
- Strange Behavior with RabbitMQ and Flask-SocketIO HOT 4
- get_received(namespace=None) does not returns the messages HOT 5
- Add type hints HOT 9
- Socket.IO test client does not run background task HOT 7
- gevent - cannot enter into function. HOT 1
- Multiple SocketIO instances connected to the same Flask server HOT 1
- python-engineio and python-socketio version matching with Flask-SocketIO >= 5.3.0 HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from flask-socketio.