blob: 00daf396bd6a2d52d628c87fa16f1e3377703898 [file] [log] [blame]
Martin v. Löwis281b2c62003-04-18 21:04:39 +00001"""Self documenting XML-RPC Server.
2
3This module can be used to create XML-RPC servers that
4serve pydoc-style documentation in response to HTTP
5GET requests. This documentation is dynamically generated
6based on the functions and methods registered with the
7server.
8
9This module is built upon the pydoc and SimpleXMLRPCServer
10modules.
11"""
12
13import pydoc
14import inspect
Martin v. Löwis281b2c62003-04-18 21:04:39 +000015import re
Martin v. Löwis9c5ea502003-05-01 05:05:09 +000016import sys
Martin v. Löwis281b2c62003-04-18 21:04:39 +000017
Andrew M. Kuchling33ad28b2004-08-31 11:38:12 +000018from SimpleXMLRPCServer import (SimpleXMLRPCServer,
19 SimpleXMLRPCRequestHandler,
20 CGIXMLRPCRequestHandler,
21 resolve_dotted_attribute)
Martin v. Löwis281b2c62003-04-18 21:04:39 +000022
23class ServerHTMLDoc(pydoc.HTMLDoc):
24 """Class used to generate pydoc HTML document for a server"""
Tim Peters0eadaac2003-04-24 16:02:54 +000025
Martin v. Löwis281b2c62003-04-18 21:04:39 +000026 def markup(self, text, escape=None, funcs={}, classes={}, methods={}):
27 """Mark up some plain text, given a context of symbols to look for.
28 Each context dictionary maps object names to anchor names."""
29 escape = escape or self.escape
30 results = []
31 here = 0
32
33 # XXX Note that this regular expressions does not allow for the
34 # hyperlinking of arbitrary strings being used as method
35 # names. Only methods with names consisting of word characters
36 # and '.'s are hyperlinked.
37 pattern = re.compile(r'\b((http|ftp)://\S+[\w/]|'
38 r'RFC[- ]?(\d+)|'
39 r'PEP[- ]?(\d+)|'
40 r'(self\.)?((?:\w|\.)+))\b')
41 while 1:
42 match = pattern.search(text, here)
43 if not match: break
44 start, end = match.span()
45 results.append(escape(text[here:start]))
46
47 all, scheme, rfc, pep, selfdot, name = match.groups()
48 if scheme:
49 url = escape(all).replace('"', '"')
50 results.append('<a href="%s">%s</a>' % (url, url))
51 elif rfc:
52 url = 'http://www.rfc-editor.org/rfc/rfc%d.txt' % int(rfc)
53 results.append('<a href="%s">%s</a>' % (url, escape(all)))
54 elif pep:
55 url = 'http://www.python.org/peps/pep-%04d.html' % int(pep)
56 results.append('<a href="%s">%s</a>' % (url, escape(all)))
57 elif text[end:end+1] == '(':
58 results.append(self.namelink(name, methods, funcs, classes))
59 elif selfdot:
60 results.append('self.<strong>%s</strong>' % name)
61 else:
62 results.append(self.namelink(name, classes))
63 here = end
64 results.append(escape(text[here:]))
65 return ''.join(results)
Tim Peters0eadaac2003-04-24 16:02:54 +000066
Georg Brandl6113ce52007-12-09 21:15:07 +000067 def docroutine(self, object, name, mod=None,
Martin v. Löwis281b2c62003-04-18 21:04:39 +000068 funcs={}, classes={}, methods={}, cl=None):
69 """Produce HTML documentation for a function or method object."""
70
71 anchor = (cl and cl.__name__ or '') + '-' + name
72 note = ''
73
Georg Brandl6113ce52007-12-09 21:15:07 +000074 title = '<a name="%s"><strong>%s</strong></a>' % (
75 self.escape(anchor), self.escape(name))
Tim Peters0eadaac2003-04-24 16:02:54 +000076
Martin v. Löwis281b2c62003-04-18 21:04:39 +000077 if inspect.ismethod(object):
78 args, varargs, varkw, defaults = inspect.getargspec(object.im_func)
79 # exclude the argument bound to the instance, it will be
80 # confusing to the non-Python user
81 argspec = inspect.formatargspec (
82 args[1:],
83 varargs,
84 varkw,
85 defaults,
86 formatvalue=self.formatvalue
87 )
88 elif inspect.isfunction(object):
89 args, varargs, varkw, defaults = inspect.getargspec(object)
90 argspec = inspect.formatargspec(
91 args, varargs, varkw, defaults, formatvalue=self.formatvalue)
92 else:
93 argspec = '(...)'
94
Raymond Hettingerf7153662005-02-07 14:16:21 +000095 if isinstance(object, tuple):
Martin v. Löwis281b2c62003-04-18 21:04:39 +000096 argspec = object[0] or argspec
97 docstring = object[1] or ""
98 else:
99 docstring = pydoc.getdoc(object)
Tim Peters0eadaac2003-04-24 16:02:54 +0000100
Martin v. Löwis281b2c62003-04-18 21:04:39 +0000101 decl = title + argspec + (note and self.grey(
102 '<font face="helvetica, arial">%s</font>' % note))
103
104 doc = self.markup(
105 docstring, self.preformat, funcs, classes, methods)
106 doc = doc and '<dd><tt>%s</tt></dd>' % doc
107 return '<dl><dt>%s</dt>%s</dl>\n' % (decl, doc)
108
109 def docserver(self, server_name, package_documentation, methods):
110 """Produce HTML documentation for an XML-RPC server."""
111
112 fdict = {}
113 for key, value in methods.items():
114 fdict[key] = '#-' + key
115 fdict[value] = fdict[key]
Tim Peters0eadaac2003-04-24 16:02:54 +0000116
Georg Brandl6113ce52007-12-09 21:15:07 +0000117 server_name = self.escape(server_name)
Tim Peters0eadaac2003-04-24 16:02:54 +0000118 head = '<big><big><strong>%s</strong></big></big>' % server_name
Martin v. Löwis281b2c62003-04-18 21:04:39 +0000119 result = self.heading(head, '#ffffff', '#7799ee')
Tim Peters0eadaac2003-04-24 16:02:54 +0000120
Martin v. Löwis281b2c62003-04-18 21:04:39 +0000121 doc = self.markup(package_documentation, self.preformat, fdict)
122 doc = doc and '<tt>%s</tt>' % doc
123 result = result + '<p>%s</p>\n' % doc
124
125 contents = []
126 method_items = methods.items()
127 method_items.sort()
128 for key, value in method_items:
129 contents.append(self.docroutine(value, key, funcs=fdict))
130 result = result + self.bigsection(
131 'Methods', '#ffffff', '#eeaa77', pydoc.join(contents))
132
133 return result
134
135class XMLRPCDocGenerator:
136 """Generates documentation for an XML-RPC server.
137
138 This class is designed as mix-in and should not
139 be constructed directly.
140 """
Tim Peters0eadaac2003-04-24 16:02:54 +0000141
Martin v. Löwis281b2c62003-04-18 21:04:39 +0000142 def __init__(self):
143 # setup variables used for HTML documentation
144 self.server_name = 'XML-RPC Server Documentation'
145 self.server_documentation = \
146 "This server exports the following methods through the XML-RPC "\
147 "protocol."
148 self.server_title = 'XML-RPC Server Documentation'
149
150 def set_server_title(self, server_title):
151 """Set the HTML title of the generated server documentation"""
152
153 self.server_title = server_title
154
155 def set_server_name(self, server_name):
156 """Set the name of the generated HTML server documentation"""
157
158 self.server_name = server_name
159
160 def set_server_documentation(self, server_documentation):
161 """Set the documentation string for the entire server."""
162
163 self.server_documentation = server_documentation
164
165 def generate_html_documentation(self):
166 """generate_html_documentation() => html documentation for the server
167
168 Generates HTML documentation for the server using introspection for
169 installed functions and instances that do not implement the
170 _dispatch method. Alternatively, instances can choose to implement
171 the _get_method_argstring(method_name) method to provide the
172 argument string used in the documentation and the
173 _methodHelp(method_name) method to provide the help text used
174 in the documentation."""
Tim Peters0eadaac2003-04-24 16:02:54 +0000175
Martin v. Löwis281b2c62003-04-18 21:04:39 +0000176 methods = {}
177
178 for method_name in self.system_listMethods():
179 if self.funcs.has_key(method_name):
180 method = self.funcs[method_name]
181 elif self.instance is not None:
182 method_info = [None, None] # argspec, documentation
183 if hasattr(self.instance, '_get_method_argstring'):
184 method_info[0] = self.instance._get_method_argstring(method_name)
185 if hasattr(self.instance, '_methodHelp'):
186 method_info[1] = self.instance._methodHelp(method_name)
187
188 method_info = tuple(method_info)
189 if method_info != (None, None):
190 method = method_info
191 elif not hasattr(self.instance, '_dispatch'):
192 try:
193 method = resolve_dotted_attribute(
194 self.instance,
195 method_name
196 )
197 except AttributeError:
198 method = method_info
199 else:
200 method = method_info
201 else:
202 assert 0, "Could not find method in self.functions and no "\
203 "instance installed"
204
205 methods[method_name] = method
206
207 documenter = ServerHTMLDoc()
208 documentation = documenter.docserver(
209 self.server_name,
210 self.server_documentation,
211 methods
212 )
Tim Peters0eadaac2003-04-24 16:02:54 +0000213
Martin v. Löwis281b2c62003-04-18 21:04:39 +0000214 return documenter.page(self.server_title, documentation)
215
216class DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
217 """XML-RPC and documentation request handler class.
218
219 Handles all HTTP POST requests and attempts to decode them as
220 XML-RPC requests.
221
222 Handles all HTTP GET requests and interprets them as requests
223 for documentation.
224 """
225
226 def do_GET(self):
227 """Handles the HTTP GET request.
228
229 Interpret all HTTP GET requests as requests for server
230 documentation.
231 """
Andrew M. Kuchling622f1442006-05-31 14:08:48 +0000232 # Check that the path is legal
233 if not self.is_rpc_path_valid():
234 self.report_404()
235 return
Tim Peters0eadaac2003-04-24 16:02:54 +0000236
Martin v. Löwis281b2c62003-04-18 21:04:39 +0000237 response = self.server.generate_html_documentation()
238 self.send_response(200)
239 self.send_header("Content-type", "text/html")
240 self.send_header("Content-length", str(len(response)))
241 self.end_headers()
242 self.wfile.write(response)
243
244 # shut down the connection
245 self.wfile.flush()
246 self.connection.shutdown(1)
247
248class DocXMLRPCServer( SimpleXMLRPCServer,
249 XMLRPCDocGenerator):
250 """XML-RPC and HTML documentation server.
251
252 Adds the ability to serve server documentation to the capabilities
253 of SimpleXMLRPCServer.
254 """
255
256 def __init__(self, addr, requestHandler=DocXMLRPCRequestHandler,
Collin Winterae041062007-03-10 14:41:48 +0000257 logRequests=1, allow_none=False, encoding=None,
258 bind_and_activate=True):
259 SimpleXMLRPCServer.__init__(self, addr, requestHandler, logRequests,
260 allow_none, encoding, bind_and_activate)
Martin v. Löwis281b2c62003-04-18 21:04:39 +0000261 XMLRPCDocGenerator.__init__(self)
Tim Peters0eadaac2003-04-24 16:02:54 +0000262
Martin v. Löwis281b2c62003-04-18 21:04:39 +0000263class DocCGIXMLRPCRequestHandler( CGIXMLRPCRequestHandler,
264 XMLRPCDocGenerator):
265 """Handler for XML-RPC data and documentation requests passed through
266 CGI"""
267
268 def handle_get(self):
269 """Handles the HTTP GET request.
270
271 Interpret all HTTP GET requests as requests for server
272 documentation.
273 """
274
275 response = self.generate_html_documentation()
276
277 print 'Content-Type: text/html'
278 print 'Content-Length: %d' % len(response)
279 print
Martin v. Löwis9c5ea502003-05-01 05:05:09 +0000280 sys.stdout.write(response)
Martin v. Löwis281b2c62003-04-18 21:04:39 +0000281
282 def __init__(self):
283 CGIXMLRPCRequestHandler.__init__(self)
284 XMLRPCDocGenerator.__init__(self)