Setting fcntl to None if not importable, adding tests module, updating README to...
[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 <code>
51         >>> import jsonrpclib
52         >>> server = jsonrpclib.Server('http://localhost:8080')
53         >>> server.add(5,6)
54         11
55         >>> print jsonrpclib.history.request
56         {"jsonrpc": "2.0", "params": [5, 6], "id": "gb3c9g37", "method": "add"}
57         >>> print jsonrpclib.history.response
58         {'jsonrpc': '2.0', 'result': 11, 'id': 'gb3c9g37'}
59         >>> server.add(x=5, y=10)
60         15
61         >>> server._notify.add(5,6)
62         # No result returned...
63         >>> batch = jsonrpclib.MultiCall(server)
64         >>> batch.add(5, 6)
65         >>> batch.ping({'key':'value'})
66         >>> batch._notify.add(4, 30)
67         >>> results = batch()
68         >>> for result in results:
69         >>> ... print result
70         11
71         {'key': 'value'}
72         # Note that there are only two responses -- this is according to spec.
73 </code>
74
75 If you need 1.0 functionality, there are a bunch of places you can pass that 
76 in, although the best is just to change the value on 
77 jsonrpclib.config.version:
78
79 <code>
80         >>> import jsonrpclib
81         >>> jsonrpclib.config.version
82         2.0
83         >>> jsonrpclib.config.version = 1.0
84         >>> server = jsonrpclib.Server('http://localhost:8080')
85         >>> server.add(7, 10)
86         17
87         >>> print jsonrpclib..history.request
88         {"params": [7, 10], "id": "thes7tl2", "method": "add"}
89         >>> print jsonrpclib.history.response
90         {'id': 'thes7tl2', 'result': 17, 'error': None}
91         >>> 
92 </code>
93
94 The equivalent loads and dumps functions also exist, although with minor 
95 modifications. The dumps arguments are almost identical, but it adds three 
96 arguments: rpcid for the 'id' key, version to specify the JSON-RPC 
97 compatibility, and notify if it's a request that you want to be a 
98 notification. 
99
100 Additionally, the loads method does not return the params and method like 
101 xmlrpclib, but instead a.) parses for errors, raising ProtocolErrors, and 
102 b.) returns the entire structure of the request / response for manual parsing.
103
104 SimpleJSONRPCServer
105 -------------------
106 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.
107
108 <code>
109         from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
110
111         server = SimpleJSONRPCServer(('localhost', 8080))
112         server.register_function(pow)
113         server.register_function(lambda x,y: x+y, 'add')
114         server.register_function(lambda x: x, 'ping')
115         server.serve_forever()
116 </code>
117
118 Class Translation
119 -----------------
120 I've recently added "automatic" class translation support, although it is 
121 turned off by default. This can be devastatingly slow if improperly used, so 
122 the following is just a short list of things to keep in mind when using it.
123
124 * Keep It (the object) Simple Stupid. (for exceptions, keep reading.)
125 * Do not require init params (for exceptions, keep reading)
126 * Getter properties without setters could be dangerous (read: not tested)
127
128 If any of the above are issues, use the _serialize method. (see usage below)
129 The server and client must BOTH have use_jsonclass configuration item on and 
130 they must both have access to the same libraries used by the objects for 
131 this to work.
132
133 If you have excessively nested arguments, it would be better to turn off the 
134 translation and manually invoke it on specific objects using 
135 jsonrpclib.jsonclass.dump / jsonrpclib.jsonclass.load (since the default 
136 behavior recursively goes through attributes and lists / dicts / tuples).
137
138 [test_obj.py]
139
140 <code>
141         # This object is /very/ simple, and the system will look through the 
142         # attributes and serialize what it can.
143         class TestObj(object):
144             foo = 'bar'
145
146         # This object requires __init__ params, so it uses the _serialize method
147         # and returns a tuple of init params and attribute values (the init params
148         # can be a dict or a list, but the attribute values must be a dict.)
149         class TestSerial(object):
150             foo = 'bar'
151             def __init__(self, *args):
152                 self.args = args
153             def _serialize(self):
154                 return (self.args, {'foo':self.foo,})
155 </code>
156
157 [usage]
158
159 <code>
160         import jsonrpclib
161         import test_obj
162
163         jsonrpclib.config.use_jsonclass = True
164
165         testobj1 = test_obj.TestObj()
166         testobj2 = test_obj.TestSerial()
167         server = jsonrpclib.Server('http://localhost:8080')
168         # The 'ping' just returns whatever is sent
169         ping1 = server.ping(testobj1)
170         ping2 = server.ping(testobj2)
171         print jsonrpclib.history.request
172         # {"jsonrpc": "2.0", "params": [{"__jsonclass__": ["test_obj.TestSerial", ["foo"]]}], "id": "a0l976iv", "method": "ping"}
173         print jsonrpclib.history.result
174         # {'jsonrpc': '2.0', 'result': <test_obj.TestSerial object at 0x2744590>, 'id': 'a0l976iv'}
175 </code>
176         
177 To turn on this behaviour, just set jsonrpclib.config.use_jsonclass to True. 
178 If you want to use a different method for serialization, just set 
179 jsonrpclib.config.serialize_method to the method name. Finally, if you are 
180 using classes that you have defined in the implementation (as in, not a 
181 separate library), you'll need to add those (on BOTH the server and the 
182 client) using the jsonrpclib.config.classes.add() method. 
183 (Examples forthcoming.)
184
185 Feedback on this "feature" is very, VERY much appreciated.
186
187 Why JSON-RPC?
188 -------------
189 In my opinion, there are several reasons to choose JSON over XML for RPC:
190
191 * Much simpler to read (I suppose this is opinion, but I know I'm right. :)
192 * Size / Bandwidth - Main reason, a JSON object representation is just much smaller.
193 * Parsing - JSON should be much quicker to parse than XML.
194 * Easy class passing with jsonclass (when enabled)
195
196 In the interest of being fair, there are also a few reasons to choose XML 
197 over JSON:
198
199 * Your server doesn't do JSON (rather obvious)
200 * Wider XML-RPC support across APIs (can we change this? :))
201 * Libraries are more established, i.e. more stable (Let's change this too.)
202
203 TESTS
204 -----
205 I've dropped almost-verbatim tests from the JSON-RPC spec 2.0 page.
206 You can run it with:
207
208         python tests.py
209
210 TODO
211 ----
212 * Use HTTP error codes on SimpleJSONRPCServer
213 * Test, test, test and optimize