Skip to content

Commit 3a2e2e0

Browse files
committed
Port to Python3 (courtesy tomassedovic, mrjoes#72)
1 parent c251c65 commit 3a2e2e0

File tree

11 files changed

+47
-24
lines changed

11 files changed

+47
-24
lines changed

examples/multiplexed/multiplexed.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import print_function
2+
13
from os import path as op
24

35
import datetime
@@ -31,7 +33,7 @@ def get_username(cls):
3133
return 'User%d' % cls.unique_id
3234

3335
def on_open(self, info):
34-
print 'Chat', repr(info)
36+
print('Chat', repr(info))
3537

3638
# Give user unique ID
3739
self.user_name = self.get_username()
@@ -54,7 +56,7 @@ def broadcast(self, msg):
5456

5557
class PingConnection(SocketConnection):
5658
def on_open(self, info):
57-
print 'Ping', repr(info)
59+
print('Ping', repr(info))
5860

5961
def on_message(self, message):
6062
now = datetime.datetime.now()
@@ -68,7 +70,7 @@ class RouterConnection(SocketConnection):
6870
'/ping': PingConnection}
6971

7072
def on_open(self, info):
71-
print 'Router', repr(info)
73+
print('Router', repr(info))
7274

7375
# Create tornadio server
7476
MyRouter = TornadioRouter(RouterConnection)

examples/rpcping/rpcping.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from __future__ import print_function
2+
13
from os import path as op
24

35
import datetime
@@ -24,7 +26,7 @@ def get(self):
2426
class PingConnection(SocketConnection):
2527
@event
2628
def ping(self, client, text):
27-
print 'Got %s from client' % text
29+
print('Got %s from client' % text)
2830

2931
now = datetime.datetime.now()
3032

tornadio2/conn.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
from inspect import ismethod, getmembers
2626

2727
from tornadio2 import proto
28+
from tornadio2.py2compat import with_metaclass
2829

2930

3031
logger = logging.getLogger('tornadio2.conn')
@@ -62,15 +63,15 @@ class EventMagicMeta(type):
6263
"""Event handler metaclass"""
6364
def __init__(cls, name, bases, attrs):
6465
# find events, also in bases
65-
is_event = lambda x: ismethod(x) and hasattr(x, '_event_name')
66+
is_event = lambda x: hasattr(x, '_event_name')
6667
events = [(e._event_name, e) for _, e in getmembers(cls, is_event)]
6768
setattr(cls, '_events', dict(events))
6869

6970
# Call base
7071
super(EventMagicMeta, cls).__init__(name, bases, attrs)
7172

7273

73-
class SocketConnection(object):
74+
class SocketConnection(with_metaclass(EventMagicMeta, object)):
7475
"""Subclass this class and define at least `on_message()` method to make a Socket.IO
7576
connection handler.
7677
@@ -96,8 +97,6 @@ def test(self, msg):
9697
sock.emit('test', {msg:'Hello World'});
9798
9899
"""
99-
__metaclass__ = EventMagicMeta
100-
101100
__endpoints__ = dict()
102101

103102
def __init__(self, session, endpoint=None):

tornadio2/flashserver.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
Flash Socket policy server implementation. Merged with minor modifications
2222
from the SocketTornad.IO project.
2323
"""
24-
from __future__ import with_statement
2524

2625
import socket
2726
import errno
@@ -64,7 +63,7 @@ def connection_ready(self, sock, _fd, _events):
6463
while True:
6564
try:
6665
connection, address = sock.accept()
67-
except socket.error, ex:
66+
except socket.error as ex:
6867
if ex[0] not in (errno.EWOULDBLOCK, errno.EAGAIN):
6968
raise
7069
return

tornadio2/persistent.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ def on_message(self, message):
144144

145145
try:
146146
self.session.raw_message(message)
147-
except Exception, ex:
147+
except Exception as ex:
148148
logger.error('Failed to handle message: ' + traceback.format_exc(ex))
149149

150150
# Close session on exception

tornadio2/polling.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,10 @@
2222
"""
2323
import time
2424
import logging
25-
import urllib
25+
try:
26+
from urllib import unquote_plus # Python 2
27+
except ImportError:
28+
from urllib.parse import unquote_plus # Python 3
2629

2730
from tornado.web import HTTPError, asynchronous
2831

@@ -295,7 +298,7 @@ def post(self, session_id):
295298
raise HTTPError(403)
296299

297300
# Grab data
298-
data = urllib.unquote_plus(data[2:]).decode('utf-8')
301+
data = unquote_plus(data[2:]).decode('utf-8')
299302

300303
# If starts with double quote, it is json encoded (socket.io workaround)
301304
if data.startswith(u'"'):

tornadio2/proto.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
Socket.IO protocol related functions
2222
"""
2323
import logging
24+
import sys
2425

2526

2627
logger = logging.getLogger('tornadio2.proto')
@@ -40,6 +41,14 @@ def default(self, o):
4041
return super(DecimalEncoder, self).default(o)
4142
json_decimal_args = {"cls": DecimalEncoder}
4243

44+
45+
if sys.version_info[0] == 2:
46+
text_type = unicode
47+
string_types = (str, unicode)
48+
else:
49+
text_type = str
50+
string_types = (str,)
51+
4352
# Packet ids
4453
DISCONNECT = '0'
4554
CONNECT = '1'
@@ -106,15 +115,15 @@ def message(endpoint, msg, message_id=None, force_json=False):
106115
'message_id': message_id or u''}
107116

108117
# Trying to send a dict over the wire ?
109-
if not isinstance(msg, (unicode, str)) and isinstance(msg, (dict, object)):
118+
if not isinstance(msg, string_types) and isinstance(msg, (dict, object)):
110119
packed_data.update({'kind': JSON,
111120
'msg': json.dumps(msg, **json_decimal_args)})
112121

113122
# for all other classes, including objects. Call str(obj)
114123
# and respect forced JSON if requested
115124
else:
116125
packed_data.update({'kind': MESSAGE if not force_json else JSON,
117-
'msg': msg if isinstance(msg, unicode) else str(msg).decode('utf-8')})
126+
'msg': msg if isinstance(msg, text_type) else str(msg).decode('utf-8')})
118127

119128
return packed_message_tpl % packed_data
120129

@@ -224,7 +233,7 @@ def decode_frames(data):
224233
225234
"""
226235
# Single message - nothing to decode here
227-
assert isinstance(data, unicode), 'frame is not unicode'
236+
assert isinstance(data, text_type), 'frame is not unicode'
228237

229238
if not data.startswith(FRAME_SEPARATOR):
230239
return [data]

tornadio2/router.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def get(self, version, *args, **kwargs):
8787

8888
# TODO: Fix heartbeat timeout. For now, it is adding 5 seconds to the client timeout.
8989
data = '%s:%d:%d:%s' % (
90-
sess.session_id,
90+
sess.session_id.decode('utf-8'),
9191
# TODO: Fix me somehow a well. 0.9.2 will drop connection is no
9292
# heartbeat was sent over
9393
settings['heartbeat_interval'] + settings['client_timeout'],

tornadio2/server.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ def __init__(self, application,
9999
io_loop=io_loop,
100100
port=flash_policy_port,
101101
policy_file=flash_policy_file)
102-
except Exception, ex:
102+
except Exception as ex:
103103
logger.error('Failed to start Flash policy server: %s', ex)
104104

105105
if auto_start:

tornadio2/session.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,10 @@
2121
Active TornadIO2 connection session.
2222
"""
2323

24-
import urlparse
24+
try:
25+
from urlparse import urlparse # Python 2
26+
except ImportError:
27+
from urllib.parse import urlparse # Python 3
2528
import logging
2629

2730

@@ -289,7 +292,7 @@ def connect_endpoint(self, url):
289292
`url`
290293
socket.io endpoint URL.
291294
"""
292-
urldata = urlparse.urlparse(url)
295+
urldata = urlparse(url)
293296

294297
endpoint = urldata.path
295298

@@ -404,7 +407,7 @@ def raw_message(self, msg):
404407
# in args
405408
if len(args) == 1 and isinstance(args[0], dict):
406409
# Fix for the http://bugs.python.org/issue4978 for older Python versions
407-
str_args = dict((str(x), y) for x, y in args[0].iteritems())
410+
str_args = dict((str(x), y) for x, y in args[0].items())
408411

409412
ack_response = conn.on_event(event['name'], kwargs=str_args)
410413
else:
@@ -429,7 +432,7 @@ def raw_message(self, msg):
429432
logger.error('Incoming error: %s' % msg_data)
430433
elif msg_type == proto.NOOP:
431434
pass
432-
except Exception, ex:
435+
except Exception as ex:
433436
logger.exception(ex)
434437

435438
# TODO: Add global exception callback?

0 commit comments

Comments
 (0)