Skip to content

Commit

Permalink
Port to Python3 (courtesy tomassedovic, mrjoes#72)
Browse files Browse the repository at this point in the history
  • Loading branch information
jafd committed Aug 16, 2020
1 parent c251c65 commit 3a2e2e0
Show file tree
Hide file tree
Showing 11 changed files with 47 additions and 24 deletions.
8 changes: 5 additions & 3 deletions examples/multiplexed/multiplexed.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import print_function

from os import path as op

import datetime
Expand Down Expand Up @@ -31,7 +33,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()
Expand All @@ -54,7 +56,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()
Expand All @@ -68,7 +70,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)
Expand Down
4 changes: 3 additions & 1 deletion examples/rpcping/rpcping.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import print_function

from os import path as op

import datetime
Expand All @@ -24,7 +26,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()

Expand Down
7 changes: 3 additions & 4 deletions tornadio2/conn.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from inspect import ismethod, getmembers

from tornadio2 import proto
from tornadio2.py2compat import with_metaclass


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

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


class SocketConnection(object):
class SocketConnection(with_metaclass(EventMagicMeta, object)):
"""Subclass this class and define at least `on_message()` method to make a Socket.IO
connection handler.
Expand All @@ -96,8 +97,6 @@ def test(self, msg):
sock.emit('test', {msg:'Hello World'});
"""
__metaclass__ = EventMagicMeta

__endpoints__ = dict()

def __init__(self, session, endpoint=None):
Expand Down
3 changes: 1 addition & 2 deletions tornadio2/flashserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
Flash Socket policy server implementation. Merged with minor modifications
from the SocketTornad.IO project.
"""
from __future__ import with_statement

import socket
import errno
Expand Down Expand Up @@ -64,7 +63,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
Expand Down
2 changes: 1 addition & 1 deletion tornadio2/persistent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions tornadio2/polling.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,10 @@
"""
import time
import logging
import urllib
try:
from urllib import unquote_plus # Python 2
except ImportError:
from urllib.parse import unquote_plus # Python 3

from tornado.web import HTTPError, asynchronous

Expand Down Expand Up @@ -295,7 +298,7 @@ def post(self, session_id):
raise HTTPError(403)

# Grab data
data = urllib.unquote_plus(data[2:]).decode('utf-8')
data = unquote_plus(data[2:]).decode('utf-8')

# If starts with double quote, it is json encoded (socket.io workaround)
if data.startswith(u'"'):
Expand Down
15 changes: 12 additions & 3 deletions tornadio2/proto.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
Socket.IO protocol related functions
"""
import logging
import sys


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


if sys.version_info[0] == 2:
text_type = unicode
string_types = (str, unicode)
else:
text_type = str
string_types = (str,)

# Packet ids
DISCONNECT = '0'
CONNECT = '1'
Expand Down Expand Up @@ -106,15 +115,15 @@ def message(endpoint, msg, message_id=None, force_json=False):
'message_id': message_id or u''}

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

# for all other classes, including objects. Call str(obj)
# 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, text_type) else str(msg).decode('utf-8')})

return packed_message_tpl % packed_data

Expand Down Expand Up @@ -224,7 +233,7 @@ def decode_frames(data):
"""
# Single message - nothing to decode here
assert isinstance(data, unicode), 'frame is not unicode'
assert isinstance(data, text_type), 'frame is not unicode'

if not data.startswith(FRAME_SEPARATOR):
return [data]
Expand Down
2 changes: 1 addition & 1 deletion tornadio2/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def get(self, version, *args, **kwargs):

# TODO: Fix heartbeat timeout. For now, it is adding 5 seconds to the client timeout.
data = '%s:%d:%d:%s' % (
sess.session_id,
sess.session_id.decode('utf-8'),
# TODO: Fix me somehow a well. 0.9.2 will drop connection is no
# heartbeat was sent over
settings['heartbeat_interval'] + settings['client_timeout'],
Expand Down
2 changes: 1 addition & 1 deletion tornadio2/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
11 changes: 7 additions & 4 deletions tornadio2/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@
Active TornadIO2 connection session.
"""

import urlparse
try:
from urlparse import urlparse # Python 2
except ImportError:
from urllib.parse import urlparse # Python 3
import logging


Expand Down Expand Up @@ -289,7 +292,7 @@ def connect_endpoint(self, url):
`url`
socket.io endpoint URL.
"""
urldata = urlparse.urlparse(url)
urldata = urlparse(url)

endpoint = urldata.path

Expand Down Expand Up @@ -404,7 +407,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 args[0].items())

ack_response = conn.on_event(event['name'], kwargs=str_args)
else:
Expand All @@ -429,7 +432,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?
Expand Down
10 changes: 8 additions & 2 deletions tornadio2/sessioncontainer.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,9 @@
def _random_key():
"""Return random session key"""
i = md5()
i.update('%s%s' % (random(), time()))
return i.hexdigest()
# Python 3 requires bytes not string, hence the encode
i.update(('%s%s' % (random(), time())).encode('utf-8'))
return i.hexdigest().encode('utf-8')


class SessionBase(object):
Expand Down Expand Up @@ -71,9 +72,14 @@ def on_delete(self, forced):
"""Triggered when object was expired or deleted."""
pass

# Python 2
def __cmp__(self, other):
return cmp(self.expiry_date, other.expiry_date)

# Python 3
def __lt__(self, other):
return self.expiry_date < other.expiry_date

def __repr__(self):
return '%f %s %d' % (getattr(self, 'expiry_date', -1),
self.session_id,
Expand Down

0 comments on commit 3a2e2e0

Please sign in to comment.