From 431606be5359d82f12aada423f722e7d35cd66cb Mon Sep 17 00:00:00 2001 From: paulocheque Date: Mon, 13 Mar 2017 14:36:16 -0300 Subject: [PATCH] Python 3 compatibility (2to3 auto) --- doc/conf.py | 16 +++++++------- examples/multiplexed/multiplexed.py | 6 ++--- examples/rpcping/rpcping.py | 2 +- tests/gen_test.py | 2 +- tests/proto_test.py | 18 +++++++-------- tornadio2/conn.py | 3 +-- tornadio2/flashserver.py | 4 ++-- tornadio2/persistent.py | 2 +- tornadio2/polling.py | 8 +++---- tornadio2/proto.py | 34 ++++++++++++++--------------- tornadio2/server.py | 2 +- tornadio2/session.py | 10 ++++----- 12 files changed, 53 insertions(+), 54 deletions(-) diff --git a/doc/conf.py b/doc/conf.py index d36732c..72229b0 100644 --- a/doc/conf.py +++ b/doc/conf.py @@ -40,8 +40,8 @@ master_doc = 'index' # General information about the project. -project = u'TornadIO2' -copyright = u'2011, Serge S. Koval' +project = 'TornadIO2' +copyright = '2011, Serge S. Koval' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -183,8 +183,8 @@ # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ - ('index', 'TornadIO2.tex', u'TornadIO2 Documentation', - u'Serge S. Koval', 'manual'), + ('index', 'TornadIO2.tex', 'TornadIO2 Documentation', + 'Serge S. Koval', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of @@ -213,8 +213,8 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ - ('index', 'tornadio2', u'TornadIO2 Documentation', - [u'Serge S. Koval'], 1) + ('index', 'tornadio2', 'TornadIO2 Documentation', + ['Serge S. Koval'], 1) ] # If true, show URL addresses after external links. @@ -227,8 +227,8 @@ # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ - ('index', 'TornadIO2', u'TornadIO2 Documentation', - u'Serge S. Koval', 'TornadIO2', 'One line description of project.', + ('index', 'TornadIO2', 'TornadIO2 Documentation', + 'Serge S. Koval', 'TornadIO2', 'One line description of project.', 'Miscellaneous'), ] diff --git a/examples/multiplexed/multiplexed.py b/examples/multiplexed/multiplexed.py index 4c5aedd..f1f4d5b 100644 --- a/examples/multiplexed/multiplexed.py +++ b/examples/multiplexed/multiplexed.py @@ -31,7 +31,7 @@ def get_username(cls): return 'User%d' % cls.unique_id def on_open(self, info): - print 'Chat', repr(info) + print(('Chat', repr(info))) # Give user unique ID self.user_name = self.get_username() @@ -54,7 +54,7 @@ def broadcast(self, msg): class PingConnection(SocketConnection): def on_open(self, info): - print 'Ping', repr(info) + print(('Ping', repr(info))) def on_message(self, message): now = datetime.datetime.now() @@ -68,7 +68,7 @@ class RouterConnection(SocketConnection): '/ping': PingConnection} def on_open(self, info): - print 'Router', repr(info) + print(('Router', repr(info))) # Create tornadio server MyRouter = TornadioRouter(RouterConnection) diff --git a/examples/rpcping/rpcping.py b/examples/rpcping/rpcping.py index 6a6f57a..ac44627 100644 --- a/examples/rpcping/rpcping.py +++ b/examples/rpcping/rpcping.py @@ -24,7 +24,7 @@ def get(self): class PingConnection(SocketConnection): @event def ping(self, client, text): - print 'Got %s from client' % text + print(('Got %s from client' % text)) now = datetime.datetime.now() diff --git a/tests/gen_test.py b/tests/gen_test.py index e2dad20..bc6e158 100644 --- a/tests/gen_test.py +++ b/tests/gen_test.py @@ -93,7 +93,7 @@ def __init__(self, queue_type): @gen.sync_engine def test(self, value): - for n in xrange(2): + for n in range(2): self.v += (yield gen.Task(self.queue_type, value)) def test(): diff --git a/tests/proto_test.py b/tests/proto_test.py index 055445d..e0a56ec 100644 --- a/tests/proto_test.py +++ b/tests/proto_test.py @@ -18,32 +18,32 @@ def test_encode_frames(): # Test multiple strings encode eq_(proto.encode_frames(['abc', 'def']), - u'\ufffd3\ufffdabc\ufffd3\ufffddef'.encode('utf-8')) + '\\ufffd3\\ufffdabc\\ufffd3\\ufffddef'.encode('utf-8')) def test_decode_frames(): # Single string - eq_(proto.decode_frames(u'abc'), [u'abc']) + eq_(proto.decode_frames('abc'), ['abc']) # Multiplie strings - eq_(proto.decode_frames(u'\ufffd3\ufffdabc\ufffd3\ufffddef'), - [u'abc', u'def']) + eq_(proto.decode_frames('\\ufffd3\\ufffdabc\\ufffd3\\ufffddef'), + ['abc', 'def']) def test_message(): # Test string message - eq_(proto.message(None, 'abc'), u'3:::abc') + eq_(proto.message(None, 'abc'), '3:::abc') - eq_(proto.message('abc', 'def'), u'3::abc:def') + eq_(proto.message('abc', 'def'), '3::abc:def') - eq_(proto.message(None, u'\u0403\u0404\u0405'), - u'3:::\u0403\u0404\u0405') + eq_(proto.message(None, '\\u0403\\u0404\\u0405'), + '3:::\\u0403\\u0404\\u0405') # TODO: Multibyte encoding fix # TODO: Fix me eq_(proto.message(None, dict(a=1, b=2)), - u'4:::%s' % proto.json_dumps(dict(a=1, b=2))) + '4:::%s' % proto.json_dumps(dict(a=1, b=2))) # TODO: Add event unit tests diff --git a/tornadio2/conn.py b/tornadio2/conn.py index b58b0b4..c32ac80 100644 --- a/tornadio2/conn.py +++ b/tornadio2/conn.py @@ -70,7 +70,7 @@ def __init__(cls, name, bases, attrs): super(EventMagicMeta, cls).__init__(name, bases, attrs) -class SocketConnection(object): +class SocketConnection(object, metaclass=EventMagicMeta): """Subclass this class and define at least `on_message()` method to make a Socket.IO connection handler. @@ -96,7 +96,6 @@ def test(self, msg): sock.emit('test', {msg:'Hello World'}); """ - __metaclass__ = EventMagicMeta __endpoints__ = dict() diff --git a/tornadio2/flashserver.py b/tornadio2/flashserver.py index 85d15de..585c267 100644 --- a/tornadio2/flashserver.py +++ b/tornadio2/flashserver.py @@ -21,7 +21,7 @@ Flash Socket policy server implementation. Merged with minor modifications from the SocketTornad.IO project. """ -from __future__ import with_statement + import socket import errno @@ -64,7 +64,7 @@ def connection_ready(self, sock, _fd, _events): while True: try: connection, address = sock.accept() - except socket.error, ex: + except socket.error as ex: if ex[0] not in (errno.EWOULDBLOCK, errno.EAGAIN): raise return diff --git a/tornadio2/persistent.py b/tornadio2/persistent.py index eb6200f..e55cb71 100644 --- a/tornadio2/persistent.py +++ b/tornadio2/persistent.py @@ -144,7 +144,7 @@ def on_message(self, message): try: self.session.raw_message(message) - except Exception, ex: + except Exception as ex: logger.error('Failed to handle message: ' + traceback.format_exc(ex)) # Close session on exception diff --git a/tornadio2/polling.py b/tornadio2/polling.py index d5c3f2f..eb1998d 100644 --- a/tornadio2/polling.py +++ b/tornadio2/polling.py @@ -22,7 +22,7 @@ """ import time import logging -import urllib +import urllib.request, urllib.parse, urllib.error from tornado.web import HTTPError, asynchronous @@ -88,7 +88,7 @@ def post(self, session_id): data = self.request.body.decode('utf-8') # IE XDomainRequest support - if data.startswith(u'data='): + if data.startswith('data='): data = data[5:] # Process packets one by one @@ -295,10 +295,10 @@ def post(self, session_id): raise HTTPError(403) # Grab data - data = urllib.unquote_plus(data[2:]).decode('utf-8') + data = urllib.parse.unquote_plus(data[2:]).decode('utf-8') # If starts with double quote, it is json encoded (socket.io workaround) - if data.startswith(u'"'): + if data.startswith('"'): data = proto.json_load(data) # Process packets one by one diff --git a/tornadio2/proto.py b/tornadio2/proto.py index ccf3137..5461d20 100644 --- a/tornadio2/proto.py +++ b/tornadio2/proto.py @@ -52,7 +52,7 @@ def default(self, o): NOOP = '8' # socket.io frame separator -FRAME_SEPARATOR = u'\ufffd' +FRAME_SEPARATOR = '\\ufffd' def disconnect(endpoint=None): @@ -61,7 +61,7 @@ def disconnect(endpoint=None): `endpoint` Optional endpoint name """ - return u'0::%s' % ( + return '0::%s' % ( endpoint or '' ) @@ -72,7 +72,7 @@ def connect(endpoint=None): `endpoint` Optional endpoint name """ - return u'1::%s' % ( + return '1::%s' % ( endpoint or '' ) @@ -80,7 +80,7 @@ def connect(endpoint=None): def heartbeat(): """Generate heartbeat message. """ - return u'2::' + return '2::' def message(endpoint, msg, message_id=None, force_json=False): @@ -99,14 +99,14 @@ def message(endpoint, msg, message_id=None, force_json=False): """ if msg is None: # TODO: Log something ? - return u'' + return '' - packed_message_tpl = u"%(kind)s:%(message_id)s:%(endpoint)s:%(msg)s" - packed_data = {'endpoint': endpoint or u'', - 'message_id': message_id or u''} + packed_message_tpl = "%(kind)s:%(message_id)s:%(endpoint)s:%(msg)s" + packed_data = {'endpoint': endpoint or '', + 'message_id': message_id or ''} # Trying to send a dict over the wire ? - if not isinstance(msg, (unicode, str)) and isinstance(msg, (dict, object)): + if not isinstance(msg, str) and isinstance(msg, (dict, object)): packed_data.update({'kind': JSON, 'msg': json.dumps(msg, **json_decimal_args)}) @@ -114,7 +114,7 @@ def message(endpoint, msg, message_id=None, force_json=False): # and respect forced JSON if requested else: packed_data.update({'kind': MESSAGE if not force_json else JSON, - 'msg': msg if isinstance(msg, unicode) else str(msg).decode('utf-8')}) + 'msg': msg if isinstance(msg, str) else str(msg).decode('utf-8')}) return packed_message_tpl % packed_data @@ -147,7 +147,7 @@ def event(endpoint, name, message_id, *args, **kwargs): args=[kwargs] ) - return u'5:%s:%s:%s' % ( + return '5:%s:%s:%s' % ( message_id or '', endpoint or '', json.dumps(evt) @@ -170,11 +170,11 @@ def ack(endpoint, message_id, ack_response=None): data = json_dumps(ack_response) - return u'6::%s:%s+%s' % (endpoint or '', + return '6::%s:%s+%s' % (endpoint or '', message_id, data) else: - return u'6::%s:%s' % (endpoint or '', + return '6::%s:%s' % (endpoint or '', message_id) @@ -188,14 +188,14 @@ def error(endpoint, reason, advice=None): `advice` Error advice """ - return u'7::%s:%s+%s' % (endpoint or '', + return '7::%s:%s+%s' % (endpoint or '', (reason or ''), (advice or '')) def noop(): """Generate noop packet.""" - return u'8::' + return '8::' def json_dumps(msg): @@ -224,7 +224,7 @@ def decode_frames(data): """ # Single message - nothing to decode here - assert isinstance(data, unicode), 'frame is not unicode' + assert isinstance(data, str), 'frame is not unicode' if not data.startswith(FRAME_SEPARATOR): return [data] @@ -267,7 +267,7 @@ def encode_frames(packets): return packets[0].encode('utf-8') # Multiple packets - frames = u''.join(u'%s%d%s%s' % (FRAME_SEPARATOR, len(p), + frames = ''.join('%s%d%s%s' % (FRAME_SEPARATOR, len(p), FRAME_SEPARATOR, p) for p in packets) diff --git a/tornadio2/server.py b/tornadio2/server.py index 98a7802..c08a2cd 100644 --- a/tornadio2/server.py +++ b/tornadio2/server.py @@ -99,7 +99,7 @@ def __init__(self, application, io_loop=io_loop, port=flash_policy_port, policy_file=flash_policy_file) - except Exception, ex: + except Exception as ex: logger.error('Failed to start Flash policy server: %s', ex) if auto_start: diff --git a/tornadio2/session.py b/tornadio2/session.py index caedb15..25ae55e 100644 --- a/tornadio2/session.py +++ b/tornadio2/session.py @@ -21,7 +21,7 @@ Active TornadIO2 connection session. """ -import urlparse +import urllib.parse import logging @@ -221,7 +221,7 @@ def close(self, endpoint=None): if endpoint is None: if not self.conn.is_closed: # Close child connections - for k in self.endpoints.keys(): + for k in list(self.endpoints.keys()): self.disconnect_endpoint(k) # Close parent connections @@ -289,7 +289,7 @@ def connect_endpoint(self, url): `url` socket.io endpoint URL. """ - urldata = urlparse.urlparse(url) + urldata = urllib.parse.urlparse(url) endpoint = urldata.path @@ -404,7 +404,7 @@ def raw_message(self, msg): # in args if len(args) == 1 and isinstance(args[0], dict): # Fix for the http://bugs.python.org/issue4978 for older Python versions - str_args = dict((str(x), y) for x, y in args[0].iteritems()) + str_args = dict((str(x), y) for x, y in list(args[0].items())) ack_response = conn.on_event(event['name'], kwargs=str_args) else: @@ -429,7 +429,7 @@ def raw_message(self, msg): logger.error('Incoming error: %s' % msg_data) elif msg_type == proto.NOOP: pass - except Exception, ex: + except Exception as ex: logger.exception(ex) # TODO: Add global exception callback?