Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

* Py3 fixes #212

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion examples/cross_origin/sock.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
from gevent import monkey; monkey.patch_all()

from bottle import Bottle, request
Expand All @@ -8,7 +9,7 @@
class Hello(namespace.BaseNamespace):

def on_hello(self, data):
print "hello", data
print("hello", data)
self.emit('greetings', {'from': 'sockets'})


Expand Down
2 changes: 1 addition & 1 deletion examples/flask_chat/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@
PORT = 5000

if __name__ == '__main__':
print 'Listening on http://127.0.0.1:%s and on port 10843 (flash policy server)' % PORT
print('Listening on http://127.0.0.1:%s and on port 10843 (flash policy server)' % PORT)
SocketIOServer(('', PORT), app, resource="socket.io").serve_forever()
2 changes: 1 addition & 1 deletion examples/pyramid_backbone_redis_chat/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

app = get_app('development.ini')

print 'Listening on port http://0.0.0.0:8080 and on port 10843 (flash policy server)'
print('Listening on port http://0.0.0.0:8080 and on port 10843 (flash policy server)')

SocketIOServer(('0.0.0.0', 8080), app,
resource="socket.io", policy_server=True,
Expand Down
2 changes: 1 addition & 1 deletion examples/pyramid_backbone_redis_chat_persistence/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

app = get_app('development.ini')

print 'Listening on port http://0.0.0.0:8080 and on port 10843 (flash policy server)'
print('Listening on port http://0.0.0.0:8080 and on port 10843 (flash policy server)')

SocketIOServer(('0.0.0.0', 8080), app,
resource="socket.io", policy_server=True,
Expand Down
7 changes: 5 additions & 2 deletions examples/simple_chat/chat.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
#!/usr/bin/python

from __future__ import print_function
from gevent import monkey; monkey.patch_all()

from socketio import socketio_manage
Expand Down Expand Up @@ -29,7 +32,7 @@ def on_user_message(self, msg):
self.socket.session['nickname'], msg)

def recv_message(self, message):
print "PING!!!", message
print("PING!!!", message)

class Application(object):
def __init__(self):
Expand Down Expand Up @@ -78,7 +81,7 @@ def not_found(start_response):


if __name__ == '__main__':
print 'Listening on port 8080 and on port 843 (flash policy server)'
print('Listening on port 8080 and on port 843 (flash policy server)')
SocketIOServer(('0.0.0.0', 8080), Application(),
resource="socket.io", policy_server=True,
policy_listener=('0.0.0.0', 10843)).serve_forever()
2 changes: 1 addition & 1 deletion examples/simple_pyramid_chat/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
if __name__ == '__main__':

app = get_app('development.ini')
print 'Listening on port http://0.0.0.0:8080 and on port 10843 (flash policy server)'
print('Listening on port http://0.0.0.0:8080 and on port 10843 (flash policy server)')

SocketIOServer(('0.0.0.0', 8080), app,
resource="socket.io", policy_server=True,
Expand Down
2 changes: 1 addition & 1 deletion examples/testapp/serve.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
if __name__ == '__main__':

app = get_app('development.ini')
print 'Listening on port http://127.0.0.1:8080 and on port 843 (flash policy server)'
print('Listening on port http://127.0.0.1:8080 and on port 843 (flash policy server)')
SocketIOServer(('127.0.0.1', 8080), app, policy_server=False,
transports=['websocket']).serve_forever()
17 changes: 14 additions & 3 deletions socketio/handler.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import sys
import re
import gevent
import urlparse
from gevent.hub import text_type

try:
import urllib.parse as urlparse
except ImportError:
import urlparse

from gevent.pywsgi import WSGIHandler
from socketio import transports
Expand Down Expand Up @@ -67,7 +72,11 @@ def write_jsonp_result(self, data, wrapper="0"):
self.start_response("200 OK", [
("Content-Type", "application/javascript"),
])
self.result = ['io.j[%s]("%s");' % (wrapper, data)]
if isinstance(wrapper, text_type):
wrapper = wrapper.encode('utf-8')
if isinstance(data, text_type):
data = data.encode('utf-8')
self.result = [(b'io.j[%s]("%s");' % (wrapper, data))]

def write_plain_result(self, data):
self.start_response("200 OK", [
Expand All @@ -77,6 +86,8 @@ def write_plain_result(self, data):
("Access-Control-Max-Age", 3600),
("Content-Type", "text/plain"),
])
if isinstance(data, text_type):
data = data.encode('utf-8')
self.result = [data]

def write_smart(self, data):
Expand Down Expand Up @@ -186,7 +197,7 @@ def handle_one_response(self):
socket.wsgi_app_greenlet = gevent.spawn(self.application,
self.environ,
start_response)
except:
except Exception:
self.handle_error(*sys.exc_info())

# we need to keep the connection open if we are an open socket
Expand Down
6 changes: 3 additions & 3 deletions socketio/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def emit_to_room(self, room, event, *args):
args=args,
endpoint=self.ns_name)
room_name = self._get_room_name(room)
for sessid, socket in self.socket.server.sockets.iteritems():
for sessid, socket in self.socket.server.sockets.items():
if 'rooms' not in socket.session:
continue
if room_name in socket.session['rooms'] and self.socket != socket:
Expand All @@ -55,7 +55,7 @@ def broadcast_event(self, event, *args):
args=args,
endpoint=self.ns_name)

for sessid, socket in self.socket.server.sockets.iteritems():
for sessid, socket in self.socket.server.sockets.items():
socket.send_packet(pkt)

def broadcast_event_not_me(self, event, *args):
Expand All @@ -68,6 +68,6 @@ def broadcast_event_not_me(self, event, *args):
args=args,
endpoint=self.ns_name)

for sessid, socket in self.socket.server.sockets.iteritems():
for sessid, socket in self.socket.server.sockets.items():
if socket is not self.socket:
socket.send_packet(pkt)
15 changes: 8 additions & 7 deletions socketio/namespace.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
import gevent
import re
import logging
Expand All @@ -21,11 +22,11 @@ class BaseNamespace(object):
:linenos:

def on_my_event(self, my_first_arg, my_second_arg):
print "This is the my_first_arg object", my_first_arg
print "This is the my_second_arg object", my_second_arg
print("This is the my_first_arg object", my_first_arg)
print("This is the my_second_arg object", my_second_arg)

def on_my_second_event(self, whatever):
print "This holds the first arg that was passed", whatever
print("This holds the first arg that was passed", whatever)

Handlers are automatically dispatched based on the name of the incoming
event. For example, a 'user message' event will be handled by
Expand All @@ -38,8 +39,8 @@ def on_my_second_event(self, whatever):
:linenos:

def on_third_event(self, packet):
print "The full packet", packet
print "See the BaseNamespace::call_method() method for details"
print("The full packet", packet)
print("See the BaseNamespace::call_method() method for details")
"""
def __init__(self, environ, ns_name, request=None):
self.environ = environ
Expand Down Expand Up @@ -167,14 +168,14 @@ def process_packet(self, packet):
elif packet_type == 'ack':
callback = self.socket._pop_ack_callback(packet['ackId'])
if not callback:
print "ERROR: No such callback for ackId %s" % packet['ackId']
print("ERROR: No such callback for ackId %s" % packet['ackId'])
return
return callback(*(packet['args']))
elif packet_type == 'disconnect':
# Force a disconnect on the namespace.
return self.call_method_with_acl('recv_disconnect', packet)
else:
print "Unprocessed packet", packet
print("Unprocessed packet", packet)
# TODO: manage the other packet types: disconnect

def process_event(self, packet):
Expand Down
8 changes: 4 additions & 4 deletions socketio/packet.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,21 @@
'noop': 8,
}

MSG_VALUES = dict((v, k) for k, v in MSG_TYPES.iteritems())
MSG_VALUES = dict((v, k) for k, v in MSG_TYPES.items())

ERROR_REASONS = {
'transport not supported': 0,
'client not handshaken': 1,
'unauthorized': 2
}

REASONS_VALUES = dict((v, k) for k, v in ERROR_REASONS.iteritems())
REASONS_VALUES = dict((v, k) for k, v in ERROR_REASONS.items())

ERROR_ADVICES = {
'reconnect': 0,
}

ADVICES_VALUES = dict((v, k) for k, v in ERROR_ADVICES.iteritems())
ADVICES_VALUES = dict((v, k) for k, v in ERROR_ADVICES.items())

socketio_packet_attributes = ['type', 'name', 'data', 'endpoint', 'args',
'ackId', 'reason', 'advice', 'qs', 'id']
Expand Down Expand Up @@ -153,7 +153,7 @@ def decode(rawstr, json_loads=default_json_loads):
elif msg_type == "5": # event
try:
data = json_loads(data)
except ValueError, e:
except ValueError as e:
print("Invalid JSON event message", data)
decoded_msg['args'] = []
else:
Expand Down
2 changes: 1 addition & 1 deletion socketio/sdjango.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def __call__(self, handler):
def socketio(request):
try:
socketio_manage(request.environ, SOCKETIO_NS, request)
except:
except Exception:
logging.getLogger("socketio").error("Exception while handling socketio connection", exc_info=True)
return HttpResponse("")

Expand Down
2 changes: 1 addition & 1 deletion socketio/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def start_accepting(self):
try:
if not self.policy_server.started:
self.policy_server.start()
except error, ex:
except error as ex:
sys.stderr.write(
'FAILED to start flash policy server: %s\n' % (ex, ))
except Exception:
Expand Down
4 changes: 2 additions & 2 deletions socketio/sgunicorn.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def run(self):
# Force kill all active the handlers
self.log.warning("Worker graceful timeout (pid:%s)" % self.pid)
[server.stop(timeout=1) for server in servers]
except:
except Exception:
pass
else:
self.socket.setblocking(1)
Expand Down Expand Up @@ -175,7 +175,7 @@ def run(self):
# Force kill all active the handlers
self.log.warning("Worker graceful timeout (pid:%s)" % self.pid)
server.stop(timeout=1)
except:
except Exception:
pass


Expand Down
5 changes: 4 additions & 1 deletion socketio/transports.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import gevent
import urllib
import urlparse
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
from geventwebsocket import WebSocketError
from gevent.queue import Empty

Expand Down
6 changes: 3 additions & 3 deletions socketio/virtsocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ def disconnect(self, silent=False):
:meth:`~socketio.namespace.BaseNamespace.disconnect`
calls.
"""
for ns_name, ns in list(self.active_ns.iteritems()):
for ns_name, ns in list(self.active_ns.items()):
ns.recv_disconnect()

def remove_namespace(self, namespace):
Expand Down Expand Up @@ -362,7 +362,7 @@ def _receiver_loop(self):
continue # or close the connection ?
try:
pkt = packet.decode(rawdata, self.json_loads)
except (ValueError, KeyError, Exception), e:
except (ValueError, KeyError, Exception) as e:
self.error('invalid_packet',
"There was a decoding error when dealing with packet "
"with event: %s... (%s)" % (rawdata[:20], e))
Expand Down Expand Up @@ -436,7 +436,7 @@ def _watcher(self):
while True:
gevent.sleep(1.0)
if not self.connected:
for ns_name, ns in list(self.active_ns.iteritems()):
for ns_name, ns in list(self.active_ns.items()):
ns.recv_disconnect()
# Killing Socket-level jobs
gevent.killall(self.jobs)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_namespace.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ def test_del_acl_method(self):
except ValueError as e:
self.assertEqual(
message,
e.message,
e.args[0],
)
else:
raise Exception("""We should not be able to delete an acl that
Expand Down
5 changes: 3 additions & 2 deletions tests/test_packet.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,8 @@ def test_encode_event(self):
'endpoint': '',
'args': [{"a":"b"}, 2,"3"]
})
self.assertEqual(encoded_message,
if encoded_message != '5:::{"name":"edwald","args":[{"a":"b"},2,"3"]}':
self.assertEqual(encoded_message,
'5:::{"args":[{"a":"b"},2,"3"],"name":"edwald"}')

def test_encode_ack(self):
Expand Down Expand Up @@ -349,7 +350,7 @@ def test_except_on_invalid_message_type(self):
try:
decoded_message = decode('99::')
except Exception as e:
self.assertEqual(e.message, "Unknown message type: 99")
self.assertEqual(e.args[0], "Unknown message type: 99")
else:
self.assertEqual(decoded_message, None,
"We should not get a valid message")
Expand Down