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

fixed problem: serializers datetime.datetime to JSON #12

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 9 additions & 11 deletions tornadio2/conn.py
Expand Up @@ -151,18 +151,16 @@ def on_message(self, message):
"""Default on_message handler. Must be overridden in your application""" """Default on_message handler. Must be overridden in your application"""
raise NotImplementedError() raise NotImplementedError()


def on_event(self, name, *args, **kwargs): def on_event(self, name, data, *args, **kwargs):
"""Default on_event handler. """Default on_event handler.


By default, it uses decorator-based approach to handle events, By default, it uses decorator-based approach to handle events,
but you can override it to implement custom event handling. but you can override it to implement custom event handling.


`name` `name`
Event name Event name
`args` `data`
Event args Event args or kwargs
`kwargs`
Event kwargs


There's small magic around event handling. There's small magic around event handling.
If you send exactly one parameter from the client side and it is dict, If you send exactly one parameter from the client side and it is dict,
Expand Down Expand Up @@ -194,19 +192,19 @@ def on_event(self, name, *args, **kwargs):


if handler: if handler:
try: try:
if args: if isinstance(data, list):
return handler(self, *args) return handler(self, *data)
else: else:
return handler(self, **kwargs) return handler(self, **data)
except TypeError: except TypeError:
if args: if isinstance(data, list):
logging.error(('Attempted to call event handler %s ' + logging.error(('Attempted to call event handler %s ' +
'with %s arguments.') % (handler, 'with %s arguments.') % (handler,
repr(args))) repr(data)))
else: else:
logging.error(('Attempted to call event handler %s ' + logging.error(('Attempted to call event handler %s ' +
'with %s arguments.') % (handler, 'with %s arguments.') % (handler,
repr(kwargs))) repr(data)))
raise raise
else: else:
logging.error('Invalid event name: %s' % name) logging.error('Invalid event name: %s' % name)
Expand Down
20 changes: 15 additions & 5 deletions tornadio2/proto.py
Expand Up @@ -21,10 +21,17 @@
Socket.IO protocol related functions Socket.IO protocol related functions
""" """
import logging import logging
import datetime
from bson import json_util

dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None


try: try:
import simplejson as json import simplejson as json
json_decimal_args = {"use_decimal": True} json_decimal_args = {
"use_decimal": True,
"default": json_util.default,
}
except ImportError: except ImportError:
import json import json
import decimal import decimal
Expand All @@ -34,7 +41,10 @@ def default(self, o):
if isinstance(o, decimal.Decimal): if isinstance(o, decimal.Decimal):
return float(o) return float(o)
return super(DecimalEncoder, self).default(o) return super(DecimalEncoder, self).default(o)
json_decimal_args = {"cls": DecimalEncoder} json_decimal_args = {
"cls": DecimalEncoder,
"default": json_util.default,
}


# Packet ids # Packet ids
DISCONNECT = '0' DISCONNECT = '0'
Expand Down Expand Up @@ -140,7 +150,7 @@ def event(endpoint, name, message_id, *args, **kwargs):
return u'5:%s:%s:%s' % ( return u'5:%s:%s:%s' % (
message_id or '', message_id or '',
endpoint or '', endpoint or '',
json.dumps(evt) json.dumps(evt, **json_decimal_args)
) )




Expand Down Expand Up @@ -194,7 +204,7 @@ def json_dumps(msg):
`msg` `msg`
Object to dump Object to dump
""" """
return json.dumps(msg) return json.dumps(msg, **json_decimal_args)




def json_load(msg): def json_load(msg):
Expand All @@ -203,7 +213,7 @@ def json_load(msg):
`msg` `msg`
json encoded object json encoded object
""" """
return json.loads(msg) return json.loads(msg, object_hook=json_util.object_hook)




def decode_frames(data): def decode_frames(data):
Expand Down
4 changes: 2 additions & 2 deletions tornadio2/session.py
Expand Up @@ -401,9 +401,9 @@ def raw_message(self, msg):
# Fix for the http://bugs.python.org/issue4978 for older Python versions # 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].iteritems())


ack_response = conn.on_event(event['name'], **str_args) ack_response = conn.on_event(event['name'], data=str_args)
else: else:
ack_response = conn.on_event(event['name'], *args) ack_response = conn.on_event(event['name'], data=args)


if msg_id: if msg_id:
if msg_id.endswith('+'): if msg_id.endswith('+'):
Expand Down