PageRenderTime 35ms CodeModel.GetById 10ms app.highlight 19ms RepoModel.GetById 1ms app.codeStats 0ms

/library/JSONService.py

http://pyjamas.googlecode.com/
Python | 110 lines | 84 code | 16 blank | 10 comment | 9 complexity | 80fa5ca27657123f9ca0b8f9c1c2cfc4 MD5 | raw file
  1from HTTPRequest import HTTPRequest
  2import pygwt
  3from JSONParser import JSONParser
  4
  5# no stream support
  6class JSONService:
  7    def __init__(self, url, handler = None):
  8        """
  9        Create a JSON remote service object.  The url is the URL that will receive
 10        POST data with the JSON request.  See the JSON-RPC spec for more information.
 11        
 12        The handler object should implement onRemoteResponse(value, requestInfo) to 
 13        accept the return value of the remote method, and 
 14        onRemoteError(code, message, requestInfo) to handle errors.
 15        """
 16        self.parser = JSONParser()
 17        self.url = url
 18        self.handler = handler
 19    
 20    def callMethod(self, method, params, handler = None):
 21        if handler == None:
 22            handler = self.handler
 23            
 24        if handler == None:
 25            return self.__sendNotify(method, params)
 26        else:
 27            return self.__sendRequest(method, params, handler)
 28    
 29    def onCompletion(self):
 30        pass
 31
 32    def __sendNotify(self, method, params):
 33        msg = {"id":None, "method":method, "params":params}
 34        msg_data = self.parser.encode(msg)
 35        if not HTTPRequest().asyncPost(self.url, msg_data, self):
 36            return -1
 37        return 1
 38
 39    def __sendRequest(self, method, params, handler):
 40        id = pygwt.getNextHashId()
 41        msg = {"id":id, "method":method, "params":params}
 42        msg_data = self.parser.encode(msg)
 43        
 44        request_info = JSONRequestInfo(id, method, handler)
 45        if not HTTPRequest().asyncPost(self.url, msg_data, JSONResponseTextHandler(request_info)):
 46            return -1
 47        return id
 48
 49
 50class JSONRequestInfo:
 51    def __init__(self, id, method, handler):
 52        self.id = id
 53        self.method = method
 54        self.handler = handler
 55    
 56
 57class JSONResponseTextHandler:
 58    def __init__(self, request):
 59        self.request = request
 60
 61    def onCompletion(self, json_str):
 62        response=JSONParser().decodeAsObject(json_str)
 63        
 64        if not response:
 65            self.request.handler.onRemoteError(0, "Server Error or Invalid Response", self.request)
 66        elif response["error"]:
 67            error = response["error"]
 68            self.request.handler.onRemoteError(error["code"], error["message"], self.request)
 69        else:
 70            self.request.handler.onRemoteResponse(response["result"], self.request)
 71    
 72    def onError(self, error_str, error_code):
 73        self.request.handler.onRemoteError(error_code, error_str, self.request)
 74
 75# reserved names: callMethod, onCompletion
 76class JSONProxy(JSONService):
 77    def __init__(self, url, methods=None):
 78        JSONService.__init__(self, url)
 79        if methods:
 80            self.__registerMethods(methods)
 81
 82    def __createMethod(self, method):
 83        JS("""
 84        return function() {
 85            var params = [];
 86            for (var n=0; n<arguments.length; n++) { params.push(arguments[n]); }
 87            if (params[params.length-1].onRemoteResponse) {
 88                var handler=params.pop();
 89                return this.__sendRequest(method, params, handler);
 90            }
 91            else {
 92                return this.__sendNotify(method, params);
 93            }
 94        };
 95        """)
 96
 97    def __registerMethods(self, methods):
 98        JS("""
 99        methods=methods.l;
100        for (var i in methods) {
101            var method = methods[i];
102            this[method]=this.__createMethod(method);
103        }
104        """)
105
106
107        
108    
109    
110