Commits

William Pitcock  committed 4fa0c2a

Add RPC message packer and unpacker.

  • Participants
  • Parent commits 1ff25c5

Comments (0)

Files changed (1)

File rpc_message.py

+#!/usr/bin/env python
+"""
+Copyright (c) 2012, 2013 TortoiseLabs LLC
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+This software is provided 'as is' and without any warranty, express or
+implied. In no event shall the authors be liable for any damages arising
+from the use of this software.
+"""
+
+import message
+
+def encode(secret, method, *args, **kwargs):
+    """
+    Encode a message.
+
+    >>> secret = 'moocows'
+    >>> encode(secret, 'moo', meow='cats')
+    '{"params": {"meow": "cats"}, "method": "moo", "signature": "6136b4544dc0ae0c1e4a855cc1b9be03d8379629c6b011c4390159ee632bfc1dea5448c41d62e57c855f79fdb450bc52e131c05d91d1cae7802076c38ec43ec0"}'
+    """
+    envelope = {'method': method, 'params': kwargs}
+    return message.dumps(envelope, secret)
+
+def decode(secret, signed_message, allow_unsigned=False):
+    """
+    Return a tuple of the method and kwargs.
+
+    >>> secret = 'moocows'
+    >>> message = '{"params": {"meow": "cats"}, "method": "moo", "signature": "6136b4544dc0ae0c1e4a855cc1b9be03d8379629c6b011c4390159ee632bfc1dea5448c41d62e57c855f79fdb450bc52e131c05d91d1cae7802076c38ec43ec0"}'
+    >>> decode(secret, message)
+    (u'moo', {u'meow': u'cats'})
+    """
+    unpack_message = message.loads(signed_message, secret)
+    method = unpack_message.pop('method', None)
+    params = unpack_message.pop('params', None)
+    return (method, params)
+
+if __name__ == '__main__':
+    import doctest
+    doctest.testmod()