Making corrections for 2.7 compatibility (which mostly means bypassing the xml parser...
[invirt/packages/python-jsonrpclib.git] / README.md
1 JSONRPClib
2 ==========
3 This library is an implementation of the JSON-RPC specification.
4 It supports both the original 1.0 specification, as well as the 
5 new (proposed) 2.0 spec, which includes batch submission, keyword
6 arguments, etc.
7
8 It is licensed under the Apache License, Version 2.0
9 (http://www.apache.org/licenses/LICENSE-2.0.html).
10
11 Communication
12 -------------
13 Feel free to send any questions, comments, or patches to our Google Group 
14 mailing list (you'll need to join to send a message): 
15 http://groups.google.com/group/jsonrpclib
16
17 Summary
18 -------
19 This library implements the JSON-RPC 2.0 proposed specification in pure Python. 
20 It is designed to be as compatible with the syntax of xmlrpclib as possible 
21 (it extends where possible), so that projects using xmlrpclib could easily be 
22 modified to use JSON and experiment with the differences.
23
24 It is backwards-compatible with the 1.0 specification, and supports all of the 
25 new proposed features of 2.0, including:
26
27 * Batch submission (via MultiCall)
28 * Keyword arguments
29 * Notifications (both in a batch and 'normal')
30 * Class translation using the 'jsonclass' key.
31
32 I've added a "SimpleJSONRPCServer", which is intended to emulate the 
33 "SimpleXMLRPCServer" from the default Python distribution.
34
35 Requirements
36 ------------
37 It supports cjson and simplejson, and looks for the parsers in that order 
38 (searching first for cjson, then for the "built-in" simplejson as json in 2.6+, 
39 and then the simplejson external library). One of these must be installed to 
40 use this library, although if you have a standard distribution of 2.6+, you 
41 should already have one. Keep in mind that cjson is supposed to be the 
42 quickest, I believe, so if you are going for full-on optimization you may 
43 want to pick it up.
44
45 Client Usage
46 ------------
47
48 This is (obviously) taken from a console session.
49
50         >>> import jsonrpclib
51         >>> server = jsonrpclib.Server('http://localhost:8080')
52         >>> server.add(5,6)
53         11
54         >>> print jsonrpclib.history.request
55         {"jsonrpc": "2.0", "params": [5, 6], "id": "gb3c9g37", "method": "add"}
56         >>> print jsonrpclib.history.response
57         {'jsonrpc': '2.0', 'result': 11, 'id': 'gb3c9g37'}
58         >>> server.add(x=5, y=10)
59         15
60         >>> server._notify.add(5,6)
61         # No result returned...
62         >>> batch = jsonrpclib.MultiCall(server)
63         >>> batch.add(5, 6)
64         >>> batch.ping({'key':'value'})
65         >>> batch._notify.add(4, 30)
66         >>> results = batch()
67         >>> for result in results:
68         >>> ... print result
69         11
70         {'key': 'value'}
71         # Note that there are only two responses -- this is according to spec.
72
73 If you need 1.0 functionality, there are a bunch of places you can pass that 
74 in, although the best is just to change the value on 
75 jsonrpclib.config.version:
76
77         >>> import jsonrpclib
78         >>> jsonrpclib.config.version
79         2.0
80         >>> jsonrpclib.config.version = 1.0
81         >>> server = jsonrpclib.Server('http://localhost:8080')
82         >>> server.add(7, 10)
83         17
84         >>> print jsonrpclib..history.request
85         {"params": [7, 10], "id": "thes7tl2", "method": "add"}
86         >>> print jsonrpclib.history.response
87         {'id': 'thes7tl2', 'result': 17, 'error': None}
88         >>> 
89
90 The equivalent loads and dumps functions also exist, although with minor 
91 modifications. The dumps arguments are almost identical, but it adds three 
92 arguments: rpcid for the 'id' key, version to specify the JSON-RPC 
93 compatibility, and notify if it's a request that you want to be a 
94 notification. 
95
96 Additionally, the loads method does not return the params and method like 
97 xmlrpclib, but instead a.) parses for errors, raising ProtocolErrors, and 
98 b.) returns the entire structure of the request / response for manual parsing.
99
100 SimpleJSONRPCServer
101 -------------------
102 This is identical in usage (or should be) to the SimpleXMLRPCServer in the default Python install. Some of the differences in features are that it obviously supports notification, batch calls, class translation (if left on), etc. Note: The import line is slightly different from the regular SimpleXMLRPCServer, since the SimpleJSONRPCServer is distributed within the jsonrpclib library.
103
104         from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
105
106         server = SimpleJSONRPCServer(('localhost', 8080))
107         server.register_function(pow)
108         server.register_function(lambda x,y: x+y, 'add')
109         server.register_function(lambda x: x, 'ping')
110         server.serve_forever()
111
112 Class Translation
113 -----------------
114 I've recently added "automatic" class translation support, although it is 
115 turned off by default. This can be devastatingly slow if improperly used, so 
116 the following is just a short list of things to keep in mind when using it.
117
118 * Keep It (the object) Simple Stupid. (for exceptions, keep reading.)
119 * Do not require init params (for exceptions, keep reading)
120 * Getter properties without setters could be dangerous (read: not tested)
121
122 If any of the above are issues, use the _serialize method. (see usage below)
123 The server and client must BOTH have use_jsonclass configuration item on and 
124 they must both have access to the same libraries used by the objects for 
125 this to work.
126
127 If you have excessively nested arguments, it would be better to turn off the 
128 translation and manually invoke it on specific objects using 
129 jsonrpclib.jsonclass.dump / jsonrpclib.jsonclass.load (since the default 
130 behavior recursively goes through attributes and lists / dicts / tuples).
131
132 [test_obj.py]
133
134         # This object is /very/ simple, and the system will look through the 
135         # attributes and serialize what it can.
136         class TestObj(object):
137             foo = 'bar'
138
139         # This object requires __init__ params, so it uses the _serialize method
140         # and returns a tuple of init params and attribute values (the init params
141         # can be a dict or a list, but the attribute values must be a dict.)
142         class TestSerial(object):
143             foo = 'bar'
144             def __init__(self, *args):
145                 self.args = args
146             def _serialize(self):
147                 return (self.args, {'foo':self.foo,})
148
149 [usage]
150
151         import jsonrpclib
152         import test_obj
153
154         jsonrpclib.config.use_jsonclass = True
155
156         testobj1 = test_obj.TestObj()
157         testobj2 = test_obj.TestSerial()
158         server = jsonrpclib.Server('http://localhost:8080')
159         # The 'ping' just returns whatever is sent
160         ping1 = server.ping(testobj1)
161         ping2 = server.ping(testobj2)
162         print jsonrpclib.history.request
163         # {"jsonrpc": "2.0", "params": [{"__jsonclass__": ["test_obj.TestSerial", ["foo"]]}], "id": "a0l976iv", "method": "ping"}
164         print jsonrpclib.history.result
165         # {'jsonrpc': '2.0', 'result': <test_obj.TestSerial object at 0x2744590>, 'id': 'a0l976iv'}
166         
167 To turn on this behaviour, just set jsonrpclib.config.use_jsonclass to True. 
168 If you want to use a different method for serialization, just set 
169 jsonrpclib.config.serialize_method to the method name. Finally, if you are 
170 using classes that you have defined in the implementation (as in, not a 
171 separate library), you'll need to add those (on BOTH the server and the 
172 client) using the jsonrpclib.config.classes.add() method. 
173 (Examples forthcoming.)
174
175 Feedback on this "feature" is very, VERY much appreciated.
176
177 Why JSON-RPC?
178 -------------
179 In my opinion, there are several reasons to choose JSON over XML for RPC:
180
181 * Much simpler to read (I suppose this is opinion, but I know I'm right. :)
182 * Size / Bandwidth - Main reason, a JSON object representation is just much smaller.
183 * Parsing - JSON should be much quicker to parse than XML.
184 * Easy class passing with jsonclass (when enabled)
185
186 In the interest of being fair, there are also a few reasons to choose XML 
187 over JSON:
188
189 * Your server doesn't do JSON (rather obvious)
190 * Wider XML-RPC support across APIs (can we change this? :))
191 * Libraries are more established, i.e. more stable (Let's change this too.)
192
193 TESTS
194 -----
195 I've dropped almost-verbatim tests from the JSON-RPC spec 2.0 page.
196 You can run it with:
197
198         python tests.py
199
200 TODO
201 ----
202 * Use HTTP error codes on SimpleJSONRPCServer
203 * Test, test, test and optimize