Code Monkey home page Code Monkey logo

flask-socketio's Introduction

Flask-SocketIO

Build status codecov

Socket.IO integration for Flask applications.

Sponsors

The following organizations are funding this project:

Socket.IO
Socket.IO
Add your company here!

Many individual sponsors also support this project through small ongoing contributions. Why not join them?

Installation

You can install this package as usual with pip:

pip install flask-socketio

Example

from flask import Flask, render_template
from flask_socketio import SocketIO, emit
    
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.event
def my_event(message):
    emit('my response', {'data': 'got it!'})

if __name__ == '__main__':
    socketio.run(app)

Resources

flask-socketio's People

Contributors

alanhdu avatar bekt avatar ben-harack avatar burrowsa avatar daavve avatar dependabot[bot] avatar dieselburner avatar epiceric avatar etseidler avatar gaberust avatar georgel9 avatar grant1219 avatar greyli avatar jeffwidman avatar jmann240 avatar keyan avatar likemybread avatar lrstanley avatar mclate avatar miguelgrinberg avatar mitenka avatar musicinmybrain avatar noirbizarre avatar patrickjahns avatar pilona avatar s7anley avatar shepwalker avatar suchow avatar timgates42 avatar wgwz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

flask-socketio's Issues

uWSGI crashing with KeyError: 'socketio'

Hey,

I'm having issues making uWSGI working with Flask-SocketIO, it throws a KeyError for socketio in socketio_manage.

These are snippets from my app.py:

from flask import Flask
#other imports here
...
from flask_socketio import SocketIO, emit

app = Flask(__name__)
#blueprints here
...

socketio = SocketIO(app)

@socketio.on('msg')
def msg_on(data):
    emit('response', "bob")

if __name__ == "__main__":
    socketio.run(app, host="0.0.0.0")

I'm running uWSGI like this:

uwsgi --gevent 100 --wsgi-file app.py --callable app 

What am I doing wrong?
I'm running uWSGI 2.0.2, Flask-SocketIO 0.2.2, gevent-socketio 0.3.6

Socket.IO 1.0

Any work being done to support socket.io v1.0 when it finally comes out?

SocketIO seems to be not working with multiple workers in gunicorn

Title says it pretty much. Using more than one worker leads to failed requests (502 bad gateway). Actually I came to the assumption that no matter which number of workers is set there will be always one valid worker while very other worker fails to serve requests. This assumption is based on the circumstance that some requests still are served when using multiple workers and the number of failed requests increases with the number of workers specified.

I'm sorry if this is a documented behavior - did not find anything about it.

Working Behind an (NginX) Proxy?

First, this has been a great library to use: very convenient and helpful. However, I've had a ton of trouble setting up an NginX (v1.4) reverse proxy, which is needed to handle SSL and other useful functions. Are there any examples of NginX config files that work with this library? I feel like I've tried and modified every socketio .conf variant on the internet at this point, but still can't get the handshake to work. For production use, being able to get this properly proxied is very important.

Sessions?

Is there a way to be able to keep track of which connection is which user? I just want a way to set a session (doesn't matter if just in Flask-SocketIO), or use some kind of other permanent authentication framework. I don't want to have to send a token along with every request, but if it is inevitable, I will end up having to do it.

Unable to send on global namespace

I have a sample program from the example to test if the socket is working in my application. If I use
@socketio.on('connect', namespace='/sockets')
def events_connect():
print 'Connected'
emit('connected', {'data': 'Connected', 'count': 0})

@socketio.on('disconnect', namespace='/sockets')
def events_disconnect():
print('Client disconnected')
and send using
socketio.emit('my_event', {'data' : )}, namespace='/sockets')

it works. However if I remove the namespace from the emit and connect/disconnect, it doesn't work. I read in the doc that the connect message will not come because of a gevent issue, would the same cause this push from the server side as well?

Problem with server-generated events in gunicorn

My Flask app can quite happily emit socket messages from within the @socketio.on() decorator, and when I run the app bare locally (with socketio.run(app)) I can also use socketio.emit('my response', {'data': 'Server generated event'}) as in the example code. However, when I use gunicorn as my server (gunicorn --worker-class socketio.sgunicorn.GeventSocketIOWorker mymodule:app), my @socketio.on()-decorated emit() works fine but my server-generated events fail silently. I have tried various namespaces for them, including no mentioned namespace, namespace="", and namespace="/test". I'm running the app with debug=False. What else can I try?

Error with Heroku

I am trying to use Flask-SocketIO with Heroku. From the documentation I assume that it by default connects to ||whatevername||.herokuapp.com and port 80. So I try to connect to it and I get an error 500. I checked the logs using heroku logs and saw that
2014-05-06T14:58:55.280572+00:00 app[web.1]: 2014-05-06 14:58:55 [7] [ERROR] Error handling request
2014-05-06T14:58:55.280578+00:00 app[web.1]: Traceback (most recent call last):
2014-05-06T14:58:55.280584+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask/app.py", line 1836, in call
2014-05-06T14:58:55.280585+00:00 app[web.1]: return self.wsgi_app(environ, start_response)
2014-05-06T14:58:55.280580+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 131, in handle_request
2014-05-06T14:58:55.280587+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/flask_socketio/init.py", line 24, in call
2014-05-06T14:58:55.280590+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/socketio/init.py", line 67, in socketio_manage
2014-05-06T14:58:55.280582+00:00 app[web.1]: respiter = self.wsgi(environ, resp.start_response)
2014-05-06T14:58:55.280589+00:00 app[web.1]: socketio_manage(environ, self.socket.get_namespaces(), self.app)
2014-05-06T14:58:55.280592+00:00 app[web.1]: socket = environ['socketio']
2014-05-06T14:58:55.280594+00:00 app[web.1]: KeyError: 'socketio'

I am running this as a gunicorn app.
My start.py has
from app import app

Can you please let me know what I am missing? This error looks like the socketio key doesn't exist in environ. Do I have to do some special configuration to get this working?

Runtime Error

I just tried to get started with Flask-SocketIO. I cloned the repository and created a virtualenv and installed the packages from requirements.txt.

All went fine and I could start the application. It looks as if the application works from the browser, but I get the following error in the logs.
How can I make this work?

127.0.0.1 - - [2014-05-29 15:08:33] "GET /socket.io/?EIO=2&transport=polling&t=1401368913567-200 HTTP/1.1" 500 161 0.001329
Traceback (most recent call last):
  File "/Users/govindaf/workspace/Flask-SocketIO/example/venv/lib/python2.7/site-packages/gevent/pywsgi.py", line 508, in handle_one_response
    self.run_application()
  File "/Users/govindaf/workspace/Flask-SocketIO/example/venv/lib/python2.7/site-packages/gevent/pywsgi.py", line 494, in run_application
    self.result = self.application(self.environ, self.start_response)
  File "/Users/govindaf/workspace/Flask-SocketIO/example/venv/lib/python2.7/site-packages/flask_socketio/__init__.py", line 27, in __call__
    raise RuntimeError('You need to use a gevent-socketio server.')
RuntimeError: You need to use a gevent-socketio server.
{'GATEWAY_INTERFACE': 'CGI/1.1',
 'HTTP_ACCEPT': '*/*',
 'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch',
 'HTTP_ACCEPT_LANGUAGE': 'de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4',
 'HTTP_CONNECTION': 'keep-alive',
 'HTTP_DNT': '1',
 'HTTP_HOST': '127.0.0.1:5000',
 'HTTP_REFERER': 'http://127.0.0.1:5000/',
 'HTTP_USER_AGENT': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36',
 'PATH_INFO': '/socket.io/',
 'QUERY_STRING': 'EIO=2&transport=polling&t=1401368919567-201',
 'REMOTE_ADDR': '127.0.0.1',
 'REMOTE_PORT': '57512',
 'REQUEST_METHOD': 'GET',
 'SCRIPT_NAME': '',
 'SERVER_NAME': '1.0.0.127.in-addr.arpa',
 'SERVER_PORT': '5000',
 'SERVER_PROTOCOL': 'HTTP/1.1',
 'SERVER_SOFTWARE': 'gevent/1.0 Python/2.7',
 'wsgi.errors': <open file '<stderr>', mode 'w' at 0x1054c71e0>,
 'wsgi.input': <gevent.pywsgi.Input object at 0x1061bc610>,
 'wsgi.multiprocess': False,
 'wsgi.multithread': False,
 'wsgi.run_once': False,
 'wsgi.url_scheme': 'http',
 'wsgi.version': (1, 0)} failed with RuntimeError

I am using Python 2.7.5 and this is the output of "pip freeze":

Flask==0.10.1
Flask-SocketIO==0.3.7
Jinja2==2.7.2
MarkupSafe==0.18
Werkzeug==0.9.4
gevent==1.0
gevent-socketio==0.3.6
gevent-websocket==0.9.2
greenlet==0.4.2
itsdangerous==0.23
ujson==1.33
wsgiref==0.1.2

'base64Encoding' is deprecated: first deprecated in iOS 7.0

I get these warning with Xcode 5

socket.IO-objc/SocketRocket/SRWebSocket.m:120:18: 'base64Encoding' is deprecated: first deprecated in iOS 7.0
socket.IO-objc/SocketRocket/SRWebSocket.m:512:29: 'base64Encoding' is deprecated: first deprecated in iOS 7.0

server broadcast not working

Simply not seeing the emit on the client side, not sure if I am missing something. (Note, the client-initiated calls are working properly)

Server:

def broadcast(movie_id, gif_id):
socketio.emit('event name', json)

Client:

var global_socket = io.connect('http://' + document.domain + ':' + location.port);
        global_socket.on('event name', function(msg) {
            console.log("event name");
        });

RuntimeError: You need to use a gevent-socketio server.

File "/home/ubuntu/bachelor-thesis/crowd-tracker/venv/local/lib/python2.7/site-packages/gevent/pywsgi.py", line 508, in handle_one_response
self.run_application()
File "/home/ubuntu/bachelor-thesis/crowd-tracker/venv/local/lib/python2.7/site-packages/geventwebsocket/handler.py", line 88, in run_application
return super(WebSocketHandler, self).run_application()
File "/home/ubuntu/bachelor-thesis/crowd-tracker/venv/local/lib/python2.7/site-packages/gevent/pywsgi.py", line 494, in run_application
self.result = self.application(self.environ, self.start_response)
File "/home/ubuntu/bachelor-thesis/crowd-tracker/venv/local/lib/python2.7/site-packages/flask/app.py", line 1836, in call
return self.wsgi_app(environ, start_response)
File "/home/ubuntu/bachelor-thesis/crowd-tracker/venv/local/lib/python2.7/site-packages/flask_socketio/init.py", line 27, in call
raise RuntimeError('You need to use a gevent-socketio server.')
RuntimeError: You need to use a gevent-socketio server.
{'GATEWAY_INTERFACE': 'CGI/1.1',
'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8',
'HTTP_ACCEPT_ENCODING': 'gzip, deflate',
'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.5',
'HTTP_CACHE_CONTROL': 'no-cache',
'HTTP_CONNECTION': 'upgrade',
'HTTP_COOKIE': 'user-id=BYH0IY80VM9RD2ZOWKLR1',
'HTTP_HOST': '127.0.0.1:8000',
'HTTP_ORIGIN': '[MANUALLY REMOVED FOR PRIVACY REASONS]',
'HTTP_PRAGMA': 'no-cache',
'HTTP_SEC_WEBSOCKET_KEY': 'ekUWDrWk7/SS5pDdOPExMA==',
'HTTP_SEC_WEBSOCKET_VERSION': '13',
'HTTP_USER_AGENT': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0',
'HTTP_VIA': '1.1 localhost.localdomain 80F42A05',
'PATH_INFO': '/socket.io/1/websocket/613508800898',
'QUERY_STRING': '',
'RAW_URI': '/socket.io/1/websocket/613508800898',
'REMOTE_ADDR': '127.0.0.1',
'REMOTE_PORT': '56014',
'REQUEST_METHOD': 'GET',
'SCRIPT_NAME': '',
'SERVER_NAME': 'localhost',
'SERVER_PORT': '8000',
'SERVER_PROTOCOL': 'HTTP/1.1',
'SERVER_SOFTWARE': 'gevent/1.0 Python/2.7',
'gunicorn.sock': <socket at 0x7f8fc0b89e90 fileno=12 sock=127.0.0.1:8000 peer=127.0.0.1:56014>,
'wsgi.errors': <open file '', mode 'w' at 0x7f8fc53c01e0>,
'wsgi.input': <gevent.pywsgi.Input object at 0x7f8fc0b37f90>,
'wsgi.multiprocess': False,
'wsgi.multithread': False,
'wsgi.run_once': False,
'wsgi.url_scheme': 'http',
'wsgi.version': (1, 0)} failed with RuntimeError

Traceback (most recent call last):
File "/home/ubuntu/bachelor-thesis/crowd-tracker/venv/local/lib/python2.7/site-packages/gevent/greenlet.py", line 327, in run
result = self._run(_self.args, *_self.kwargs)
File "/home/ubuntu/bachelor-thesis/crowd-tracker/venv/local/lib/python2.7/site-packages/socketio/server.py", line 124, in handle
handler.handle()
File "/home/ubuntu/bachelor-thesis/crowd-tracker/venv/local/lib/python2.7/site-packages/gevent/pywsgi.py", line 184, in handle
result = self.handle_one_request()
File "/home/ubuntu/bachelor-thesis/crowd-tracker/venv/local/lib/python2.7/site-packages/gevent/pywsgi.py", line 321, in handle_one_request
self.handle_one_response()
File "/home/ubuntu/bachelor-thesis/crowd-tracker/venv/local/lib/python2.7/site-packages/socketio/handler.py", line 170, in handle_one_response
self.transport.do_exchange(socket, request_method)
File "/home/ubuntu/bachelor-thesis/crowd-tracker/venv/local/lib/python2.7/site-packages/socketio/transports.py", line 241, in do_exchange
websocket = self.handler.environ['wsgi.websocket']
KeyError: 'wsgi.websocket'
<Greenlet at 0x7f8fc1918410: <bound method SocketIOServer.handle of <SocketIOServer at 0x7f8fc0b89f90 fileno=5 address=127.0.0.1:8000>>(<socket at 0x7f8fc0b89e90 fileno=[Errno 9] Bad fil, ('127.0.0.1', 56014))> failed with KeyError

I use both a Gevent worker with gunicorn (--worker-class socketio.sgunicorn.GeventSocketIOWorker app:app -w 1) as well as the 0.9.16 socket io library. This error is also not consistent - one of my clients caused it. I can't reproduce it.

Gunicorn runs behind an nginx proxy.

Since this is a critical error for my application and we have a deadly deadline coming quick help is much appreciated.

Request object has no attribute namespace/Client says its connected but server doesn't

Here is my code:

from flask import Flask
from flask import render_template, redirect, url_for
from flask import request
from flask import Response
from flask.ext.socketio import SocketIO, emit
import os
import workout as w

tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(file)), 'templates')
app = Flask(name, template_folder=tmpl_dir)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@app.route('/')
def home():
print ("Home")
return render_template('home.html')

@app.route('/workout', methods = ['POST'])
def workout():
emit('movement', 'That worked')
w.start_workout(5, 10)
return redirect(url_for('home'))

@socketio.on('connect', namespace='/')
def connect():
print ("We have connected to socketio")

if (name == "main"):
app.debug = True
socketio.run(app)

My Summary

we_are_connected is not firing although socket.on(connect, ....) in the client is executing the callback

Error(The part of it that matters)

emit('movement', 'That worked')
File "/usr/lib/python2.7/site-packages/flask_socketio/init.py", line 230, in emit
return request.namespace.emit(event, _args, *kwargs)
File "/usr/lib/python2.7/site-packages/werkzeug/local.py", line 338, in getattr
return getattr(self.get_current_object(), name)
AttributeError: 'Request' object has no attribute 'namespace'
{'CONTENT_LENGTH': '23',
'CONTENT_TYPE': 'application/x-www-form-urlencoded',
'GATEWAY_INTERFACE': 'CGI/1.1',
'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,
/
;q=0.8',
'HTTP_ACCEPT_ENCODING': 'gzip,deflate,sdch',
'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8',
'HTTP_CACHE_CONTROL': 'max-age=0',
'HTTP_CONNECTION': 'keep-alive',
'HTTP_HOST': 'localhost:5000',
'HTTP_ORIGIN': 'http://localhost:5000',
'HTTP_REFERER': 'http://localhost:5000/',
'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36',
'PATH_INFO': '/workout',
'QUERY_STRING': '',
'REMOTE_ADDR': '127.0.0.1',
'REMOTE_PORT': '52426',
'REQUEST_METHOD': 'POST',
'SCRIPT_NAME': '',
'SERVER_NAME': 'localhost.localdomain',
'SERVER_PORT': '5000',
'SERVER_PROTOCOL': 'HTTP/1.1',
'SERVER_SOFTWARE': 'gevent/1.0 Python/2.7',
'werkzeug.request': <Request 'http://localhost:5000/workout' [POST]>,
'wsgi.errors': <open file '', mode 'w' at 0xb73780d0>,
'wsgi.input': <gevent.pywsgi.Input object at 0xb6872c8c>,
'wsgi.multiprocess': False,
'wsgi.multithread': False,
'wsgi.run_once': False,
'wsgi.url_scheme': 'http',
'wsgi.version': (1, 0)} failed with AttributeError

Broken with gunicorn

I'm not sure if this is an issue in Flask-SocketIO, or in gevent-socketio... but given an app that I've initialized with SocketIO, like so:

from flask.ext.socketio import SocketIO
...
app = Flask(__name__)
...
socketio = SocketIO(app)

When I run my Flask app with gunicorn, I get the following stack traces when hitting it with websocket/socket.io traffic:

Traceback (most recent call last):
  File "/home/ereyes/work/env/local/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 131, in handle_request
    respiter = self.wsgi(environ, resp.start_response)
  File "/home/ereyes/work/env/local/lib/python2.7/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "/home/ereyes/work/env/local/lib/python2.7/site-packages/flask_socketio/__init__.py", line 24, in __call__
    socketio_manage(environ, self.socket.get_namespaces(), self.app)
  File "/home/ereyes/work/env/local/lib/python2.7/site-packages/socketio/__init__.py", line 67, in socketio_manage
    socket = environ['socketio']
KeyError: 'socketio'

I see that in call you are hitting socketio_manage() and the first thing it does is:

socket = environ['socketio']

And according to its pydocs, environ is:

    The ``environ`` variable is the WSGI ``environ``.  It is used to extract
    Socket object from the underlying server (as the 'socketio' key), and will
    be attached to both the ``Socket`` and ``Namespace`` objects.

Am I doing something wrong, or is there something busted in the SocketIO() constructor?

Session context from within socketio.on wrapper is not persisted

When using a server with mixed socketio.on endpoint wrappers as well as standard flask endpoint wrappers, any session variables set within the flask endpoint function can be seen from within a socketio endpoint function. However, any session variables set within a socketio endpoint are not persisted to the session store, and thus changes cannot be seen from within the standard flask endpoint functions. It seems that any modifications to the session while inside the socketio.on context are only stored within the flask server's memory, as the changes are lost when the server is restarted, while any changes to the session var that were made from within a standard flask context stick.

dynamic namespacing

Is it possible to have dynamic namespacing on the client side and catch some part of it as a variable on the backend?

Client declares the namespace /job/1 and the server has something like /job/{id} where the id is a variable?

Spawning a broadcast

Is it possible to spawn a thread that will constantly emit events to all connected clients?
Since that broadcast is started at the same time as the app, the is no context associated to it and we cannot act after an action has been received from a client.

thanks

Possible to emit from a Celery task in Flask?

Trying to emit from a Celery task in Flask. Not sure if this is possible. Here's my simplified code:

@celery.task()
def do_stuff():
    logger.info('emmittting')
    socketio.emit('my response', {'data': user_cache_key})

I'm using Gunicorn + Celery + SocketIO + Redis (broker + result backend for Celery). Is this even possible? I'm not sure if gevent can communicate to/from a celery worker.

I'm hoping to use websockets to track the progress of long-running Celery tasks.

Can callbacks decorated by @socketio.on('X', namespace='/Y') and routes be called by multiple threads ?

I'd like to maintain and modify an in memory data structore, a bit like what FlaskSocketIO does with rooms, so I need to know if this structure needs to be thread safe, I assume the answer is no, since FlaskSocketIO modifies the rooms set, here :
https://github.com/miguelgrinberg/Flask-SocketIO/blob/master/flask_socketio/__init__.py#L37

on join_room and leave_room calls. So the question is, does my data structure manipulated my subscribes and broadcast need to be thread safe ?

can not use it with celery.

from flask.ext.socketio import SocketIO, emit
from flask import Flask
from celery import Celery



def make_celery(app):
    celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)
    celery.Task = ContextTask
    return celery


app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config.update(
    CELERY_BROKER_URL='redis://localhost:6379/0',
    CELERY_RESULT_BACKEND='redis://localhost:6379/0'
)
# socketio = SocketIO(app)
celery = make_celery(app)

celery hangs with:

...
[tasks]
  . celery.backend_cleanup
  . celery.chain
  . celery.chord
  . celery.chord_unlock
  . celery.chunks
  . celery.group
  . celery.map
  . celery.starmap
  . server.add_together

[2014-02-13 01:51:27,420: DEBUG/MainProcess] | Worker: Starting Pool

Add testing methods/examples

I'm currently attempting to write a test case for a method with the @socketio.on decorator, but there are no simple methods to generate a request that would result in routing to that method.

with app.test_client() as c:
    s = c.websocket('/namespace')
    s.emit('event', {'stuff':'here'})
    # assert stuff

Failed to Debug under WingIDE for setting “app.debug = True”

Windows8/Python2.7 64bit/WingIDE, using the build-in example in Flask-SocketIO.
I found that when using WingIDE, the breakpoints I set does not work.
Reason: flask_socketio/init.py run() invoked run_with_reloader(), whick make another python.exe process.
So I comments the 'app.debug = True' line, and all breakpoints become OK.

app = Flask(__name__)
#app.debug = True
app.config['SECRET_KEY'] = 'dosjfsodfa097324r3rn09dv66s8839bd'
socketio = SocketIO(app)
thread = None

Server Push Example

Can you provide an example where the server just pushes data to the client(s) ? I would like to broadcast a message if an (server-side) event happens. No client-side event has happened afore.

Broadcast does not work with gunicorn

Maybe it is a regression of #14. I tested it with current Flask-SocketIO release and with master branch. Both works fine with development server but don't send broadcast with gunicorn.

-e git+https://github.com/miguelgrinberg/Flask-SocketIO.git@2a08c09fc170945c2be9a4a790790a92c2967372#egg=Flask_SocketIO-master
gevent==1.0.1
gevent-socketio==0.3.6
gevent-websocket==0.9.3
greenlet==0.4.2
gunicorn==19.0.0

gracefull error handling for missing arguments from client

Flask-socketio raises a TypeError when a method has a required parameter and the client does not provide it:

for example:

@socketio.on('login', namespace='/test')
def login(message):
....

will fail with TypeError when the client only sends 'login' without a second parameter / message

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/gevent/greenlet.py", line 327, in run
    result = self._run(*self.args, **self.kwargs)
  File "/usr/local/lib/python2.7/dist-packages/socketio/virtsocket.py", line 403, in _receiver_loop
    retval = pkt_ns.process_packet(pkt)
  File "/usr/local/lib/python2.7/dist-packages/socketio/namespace.py", line 155, in process_packet
    return self.process_event(packet)
  File "/usr/local/lib/python2.7/dist-packages/flask_socketio/__init__.py", line 53, in process_event
    return self.socketio._dispatch_message(app, self, message, args)
  File "/usr/local/lib/python2.7/dist-packages/flask_socketio/__init__.py", line 122, in _dispatch_message
    ret = self.messages[namespace.ns_name][message](*args)
TypeError: login() takes exactly 1 argument (0 given)
<Greenlet at 0x2672230: <bound method Socket._receiver_loop of <socketio.virtsocket.Socket object at 0x2775290>>> failed with TypeError

Flask-SocketIO doesn't work well with Flask-Assets

Building assets leads to a freeze, whether it's started via {% assets ... %} or via environment['bundle'].urls().
I'm using Flask-SocketIO 0.4.0 and Flask-Assets 0.10 on Windows 7. I'll check if the issue persists on Ubuntu.

uwsgi deployment

I'm trying to deploy a Flask app with uwsgi (+nginx), but I was unable to do it (#20).

In one of your tutorials (http://blog.miguelgrinberg.com/post/easy-websockets-with-flask-and-gevent/page/4), you say it is possible to run with uwsgi, but in #20 you say it is not possible. Can you clear the status of this issue?

Do you know flask-uwsgi-websocket project? Is it possible to take some ideas from there to make it work with Flask-SocketIO? https://github.com/zeekay/flask-uwsgi-websocket/

SocketIO makes Celery worker hang

I had an application that uses Celery that was working fine. I wanted to add Flask-SocketIO to implement a Celery unrelated feature. However, this made Celery worker hang.

More specifically, I invoke the celery worker by calling

celery worker -A app.celery_app -l info

in a directory which has the package app as a subdirectory and that initializes celery_app in its __init__.py. This would normally show me some info and eventually say

[2014-10-17 17:02:35,394: INFO/MainProcess] mingle: all alone
[2014-10-17 17:02:35,410: WARNING/MainProcess] celery@mymachine ready.

However, by adding

from flask.ext.socketio import SocketIO

to the top of the app/__init__.py file, these two last lines would never show and Celery couldn't be killed by pressing Ctrl-C once (which would make it wait for tasks) or twice (which would make it quit immediately). The Celery Worker will hang. Literally, commenting out this one import makes all the difference.

I think this is relatively unexpected. Is there a way around? Is that a problem with Flask-SocketIO?

For completeness, the rest of app\__init__.py looks like this:

from flask import Flask
from flask_login import LoginManager, login_required, login_user, logout_user
from flask.ext.sqlalchemy import SQLAlchemy
# from flask.ext.socketio import SocketIO  # uncommenting this causes celery worker to hang

# as per http://flask.pocoo.org/docs/0.10/patterns/celery/
# but running with RabbitMQ as a broker, namely
# celery = Celery(app.import_name, broker=app.config['CELERY_BROKER_URL'])
# becomes
# celery = Celery(app.import_name)
from app.celery import make_celery  

# create the flask application itself
app = Flask(__name__)
app.config.from_object('app.config')  # no Flask-SocketIO or Celery config here

# initialize login manager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = '/login'

# database
db = SQLAlchemy(app)

from app.celery import make_celery
celery_app = make_celery(app)

from app import tasks  # Celery tasks
from app import models  # sqlalchemy

I am relatively new to Python/Flask/Celery/SocketIO, so maybe I'm just missing something obvious.

I'm running Python 2.7 on Windows. Also, for what it's worth, it seems socket io also causes a problem with debugging the __init__ and the main files in pycharm, which I think might be related. Perhaps the immediate server restart is a problem? Later in the run, I can debug views just fine.

App runner does not log server's IP/port to console?

I'm wondering why the run method does not log the IP/port of the server to the console when it runs the app, like the regular Flask version does? I find that helpful sometimes.

Love this library, thank you so much for sharing it!

Thanks

Lazy-loading

Is there any way to lazy-load the views, rather than load them all, up-front? Normal Flask has a hack to do this... Does this?

Beagle Bone Black and Rpi - Socket Fails

I have not been able to get the example app to establish a socket on either a Beagle Bone Black or a Raspberry Pi. I have been able to get it to work on a vanilla Ubuntu install.

The client keeps falling back to xhr polling; however, neither the server generated messages nor the echo message come back to the client.

Is there a known issue with gevent for these two devices?

Thanks,

John

Error when terminating application

Hi,

when running the example from github: https://github.com/miguelgrinberg/Flask-SocketIO I got some problem: The application runs fine but I seem unable to terminate the server properly. This is what I get: http://pastebin.com/XwWtp0H0

I run the application by "python app.py" and terminate it via ctrl + C.

I'm on ubuntu 13.10 with python 2.7.5. I used virtualenv with -r and the requirements.txt so I suppose everything should be okay with regards to modules.

Any help is appreciated.

Send message to speciffic connections

Is there a way to choose which connection to send a message to?

I'd like to be able to pair up users and periodically send messages to the pair of connections, and also notify one user if the other user disconnects.

I thought about broadcasting and filtering on the client side for the messaging piece, and using a ping message to see which users are still connected.

Is there a better way of doing this?

Reconnect

It will be great to have a feature where it tries to reconnect a few times on disconnect

List of users in a room

What is the best way to get a list of connected users.

Currently I have an array that adds the user when they connect and remove them when they disconnect but the issue is that when users refresh they are connected again but then the previous session triggers a disconnect so the connected user is removed from the array.

Here is my horrible code

@socketio.on('join', namespace='/chat')
def join(room):
    join_room(room)
    if current_user.is_authenticated:
        if current_user.username not in connected_users:
            connected_users.append(current_user.username)
            print(current_user.username + ' has joined ' + room)
            send(current_user.username + ' has joined', room=room)
    print(connected_users)

@socketio.on('disconnect', namespace='/chat')
def disconnect():
    print('Client disconnected')
    if current_user.is_authenticated:
        if current_user.username in connected_users:
            connected_users.remove(current_user.username)
            print(current_user.username + ' has left the room.')
            send(current_user.username + ' has left the room.', room=room)
    print(connected_users)

Sorry if this does not belong here

Emit failing to serialize SQLAlchemy models

I have a custom json_encoder setting for Flask that I use to serialize my SQLAlchemy models, and if I use flask's jsonify method my serializer works as expected.

Flask-SocketIO seems to not use my serializer, instead (IIRC) using python's own serializer.

Is there any way to change which serializer Flask-SocketIO uses?

Direct message from server to client not working

Hi Miguel,
I'm trying to send messages directly from the server, like you say in the documentation:

Sometimes the server needs to be the originator of a message. This can be useful to send a notification to clients of an event that originated in the server. The socketio.send() and socketio.emit() methods can be used to broadcast to all connected clients:

def some_function():
socketio.emit('some event', {'data': 42})

I do something like this inside my own function:

socketio.send('my response', {'data': 42})

in this case socketio is the one that I define like socketio = SocketIO(app).
Unfortunately the message are not sent to the client.

The normal communication client/server, like this works perfectly fine:

@socketio.on('my event')
def test_message(message):
emit('my response', {'data': message['data']})

Any suggestion?
Thanks a lot

Mauro

error: no handlers could be found for logger 'socketio.virtsocket'

Hi Miguel,
This probably isn't a new issue, but I'm just keeping getting this error:"no handlers could be found for logger 'socketio.virtsocket'" and have no idea what went wrong.

P.S I have added javascript code in the html file. And the sytax and order of my imports seem fine.

Jquery is local, and the source of socket.io is:

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min.js"></script>

Could you give me any suggestions?

Thanks!

missing module socketio

I can't import flask-socketio because of a missing socketio package.

(env)[cydrobolt@new-host-2 pychattr-doge]$ python
Python 2.7.5 (default, Jun 25 2014, 10:19:55) 
[GCC 4.8.2 20131212 (Red Hat 4.8.2-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from flask import Flask, render_template
>>> from flask.ext.socketio import SocketIO, emit
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/cydrobolt/PyDev/pychattr-doge/env/lib/python2.7/site-packages/flask/exthook.py", line 81, in load_module
    reraise(exc_type, exc_value, tb.tb_next)
  File "/home/cydrobolt/PyDev/pychattr-doge/env/lib/python2.7/site-packages/flask_socketio/__init__.py", line 5, in <module>
    from socketio import socketio_manage
ImportError: No module named socketio
>>> quit()
Exception KeyError: KeyError(140084549336112,) in <module 'threading' from '/usr/lib64/python2.7/threading.pyc'> ignored

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.