Login

general-purpose django XMLRC dispatcher

Author:
teepark
Posted:
February 13, 2009
Language:
Python
Version:
1.0
Tags:
xmlrpc
Score:
1 (after 1 ratings)

create an instance of this class: rpcserver = XMLRPC() then define handlers on it with the register decorator:

@rpcserver.register("pingback.ping")
def handle_pingback(sourceURI, targetURI)
    # ...

de-serialization of the arguments and serialization of the return values is handled by the XMLRPC object, so just expect python built-in types as your arguments and use them as your return values. you can also raise instances of xmlrpclib.Fault from within your handlers and a proper xmlrpc fault will be sent out as the response.

then you can use rpcserver.view in your urlconf to offer up your XML-RPC service at a URL:

urlpatterns = patterns('', 
    url(r'^$', rpcserver.view, name="xmlrpc"),
    # ...
)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from xmlrpclib import loads, dumps, Fault, ResponseError

from django.http import HttpResponse, HttpResponseNotAllowed
from django.utils.functional import wraps
from django.utils.html import strip_spaces_between_tags


METHOD_NOT_SUPPORTED = Fault(0, "method not supported")

class XMLRPC(object):
    def __init__(self):
        self.handlers = {}

    def register(self, xmlrpcname):
        "decorator to add an XML-RPC method"
        def inner(func):
            self.handlers[xmlrpcname] = func
            return func
        return wraps(func)(inner)

    def view(self, request):
        "view function for handling an XML-RPC request"
        if request.method != "POST":
            return HttpResponseNotAllowed("POST")

        try:
            args, method = loads(request.raw_post_data)
        except ResponseError:
            return HttpResponseNotAllowed("XML-RPC")

        if method is None:
            return HttpResponseNotAllowed("XML-RPC")

        if method not in self.handlers:
            result = METHOD_NOT_SUPPORTED
        else:
            try:
                result = self.handlers[method](*args)
            except Fault, fault:
                result = fault

        result = isinstance(result, tuple) and result or (result,)
        result = strip_spaces_between_tags(dumps(result, methodresponse=True))

        response = HttpResponse(mimetype="text/xml")
        response.write(result)
        response["Content-Length"] = len(response.content)
        return response

More like this

  1. In-memory XML-RPC server based on URL by diverman 4 years, 11 months ago
  2. Format transition middleware by limodou 8 years, 3 months ago
  3. An XML-RPC Decorator by blinks 8 years, 2 months ago
  4. template tag for highlighting currently active page by adunar 6 years, 7 months ago
  5. Subdirectory and subcontext include template tag with examples by t_rybik 5 years, 2 months ago

Comments

Please login first before commenting.