~ubuntu-branches/debian/jessie/web2py/jessie

« back to all changes in this revision

Viewing changes to gluon/contrib/simplejsonrpc.py

  • Committer: Package Import Robot
  • Author(s): José L. Redrejo Rodríguez
  • Date: 2011-11-04 10:12:01 UTC
  • mfrom: (1.1.10)
  • Revision ID: package-import@ubuntu.com-20111104101201-ym8q3030ik8sc10u
Tags: 1.99.2.1-1
* Updated upstream sources with real 1.99.2 version
* Ensure python-gtk2 is not needed to run web2py, fixing 
  debian/patches/gtk_gui (Closes: #646931)
* Refreshed debian/patches/avoid_updating patch

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/python
 
2
# -*- coding: utf-8 -*-
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU Lesser General Public License as published by the
 
5
# Free Software Foundation; either version 3, or (at your option) any later
 
6
# version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful, but
 
9
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTIBILITY
 
10
# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 
11
# for more details.
 
12
 
 
13
"Pythonic simple JSON RPC Client implementation"
 
14
 
 
15
__author__ = "Mariano Reingart (reingart@gmail.com)"
 
16
__copyright__ = "Copyright (C) 2011 Mariano Reingart"
 
17
__license__ = "LGPL 3.0"
 
18
__version__ = "0.04"
 
19
 
 
20
 
 
21
import urllib
 
22
from xmlrpclib import Transport, SafeTransport
 
23
from cStringIO import StringIO
 
24
import random
 
25
import sys
 
26
try:
 
27
    import gluon.contrib.simplejson as json     # try web2py json serializer 
 
28
except ImportError:
 
29
    try:
 
30
        import json                             # try stdlib (py2.6)
 
31
    except:
 
32
        import simplejson as json               # try external module
 
33
 
 
34
 
 
35
class JSONRPCError(RuntimeError):
 
36
    "Error object for remote procedure call fail"
 
37
    def __init__(self, code, message):
 
38
        self.code = code
 
39
        self.message = message
 
40
    def __unicode__(self):
 
41
        return u"%s: %s" % (self.code, self.message)
 
42
    def __str__(self):
 
43
        return self.__unicode__().encode("ascii","ignore")        
 
44
 
 
45
 
 
46
class JSONDummyParser:
 
47
    "json wrapper for xmlrpclib parser interfase"
 
48
    def __init__(self):
 
49
        self.buf = StringIO()
 
50
    def feed(self, data):
 
51
        self.buf.write(data)
 
52
    def close(self):
 
53
        return self.buf.getvalue()
 
54
 
 
55
 
 
56
class JSONTransportMixin:
 
57
    "json wrapper for xmlrpclib transport interfase"
 
58
    
 
59
    def send_content(self, connection, request_body):
 
60
        connection.putheader("Content-Type", "application/json")
 
61
        connection.putheader("Content-Length", str(len(request_body)))
 
62
        connection.endheaders()           
 
63
        if request_body:
 
64
            connection.send(request_body)
 
65
        # todo: add gzip compression
 
66
 
 
67
    def getparser(self):
 
68
        # get parser and unmarshaller
 
69
        parser = JSONDummyParser()
 
70
        return parser, parser
 
71
 
 
72
 
 
73
class JSONTransport(JSONTransportMixin, Transport):
 
74
    pass
 
75
 
 
76
class JSONSafeTransport(JSONTransportMixin, SafeTransport):
 
77
    pass
 
78
 
 
79
    
 
80
class ServerProxy(object):
 
81
    "JSON RPC Simple Client Service Proxy"
 
82
 
 
83
    def __init__(self,  uri, transport=None, encoding=None, verbose=0):
 
84
        self.location = uri             # server location (url)
 
85
        self.trace = verbose            # show debug messages
 
86
        self.exceptions = True          # raise errors? (JSONRPCError)
 
87
        self.timeout = None
 
88
        self.json_request = self.json_response = ''
 
89
 
 
90
        type, uri = urllib.splittype(uri)
 
91
        if type not in ("http", "https"):
 
92
            raise IOError, "unsupported JSON-RPC protocol"
 
93
        self.__host, self.__handler = urllib.splithost(uri)
 
94
 
 
95
        if transport is None:
 
96
            if type == "https":
 
97
                transport = JSONSafeTransport()
 
98
            else:
 
99
                transport = JSONTransport()
 
100
        self.__transport = transport
 
101
        self.__encoding = encoding
 
102
        self.__verbose = verbose                
 
103
 
 
104
    def __getattr__(self, attr):
 
105
        "pseudo method that can be called"
 
106
        return lambda *args: self.call(attr, *args)
 
107
    
 
108
    def call(self, method, *args):
 
109
        "JSON RPC communication (method invocation)"
 
110
 
 
111
        # build data sent to the service
 
112
        request_id = random.randint(0, sys.maxint)
 
113
        data = {'id': request_id, 'method': method, 'params': args, }
 
114
        request = json.dumps(data)
 
115
 
 
116
        # make HTTP request (retry if connection is lost)
 
117
        response = self.__transport.request(
 
118
            self.__host,
 
119
            self.__handler,
 
120
            request,
 
121
            verbose=self.__verbose
 
122
            )
 
123
      
 
124
        # store plain request and response for further debugging
 
125
        self.json_request = request
 
126
        self.json_response = response
 
127
 
 
128
        # parse json data coming from service 
 
129
        # {'version': '1.1', 'id': id, 'result': result, 'error': None}
 
130
        response = json.loads(response)
 
131
        
 
132
        if response['id'] != request_id:
 
133
            raise JSONRPCError(0, "JSON Request ID != Response ID")
 
134
 
 
135
        self.error = response.get('error', {})
 
136
        if self.error and self.exceptions:
 
137
            raise JSONRPCError(self.error.get('code', 0), self.error.get('message', ''))
 
138
 
 
139
        return response.get('result')
 
140
 
 
141
 
 
142
if __name__ == "__main__":
 
143
    # basic tests:
 
144
    location = "http://www.web2py.com.ar/webservices/sample/call/jsonrpc"
 
145
    client = ServerProxy(location, verbose='--verbose' in sys.argv,)
 
146
    print client.add(1, 2)
 
147