def dispatch(self, request, method='', json_encoder=None): from django.http import HttpResponse json_encoder = json_encoder or self.json_encoder try: # in case we do something json doesn't like, we always get back valid json-rpc response response = self.empty_response() if request.method.lower() == 'get': valid, D = self.validate_get(request, method) if not valid: raise InvalidRequestError('The method you are trying to access is ' 'not availble by GET requests') elif not request.method.lower() == 'post': raise RequestPostError else: try: D = loads(request.raw_post_data) except: raise InvalidRequestError if type(D) is list: response = [self.response_dict(request, d, is_batch=True, json_encoder=json_encoder)[0] for d in D] status = 200 else: response, status = self.response_dict(request, D, json_encoder=json_encoder) if response is None and (not u'id' in D or D[u'id'] is None): # a notification return HttpResponse('', status=status) json_rpc = dumps(response, cls=json_encoder) except Error, e: signals.got_request_exception.send(sender=self.__class__, request=request) response['error'] = e.json_rpc_format status = e.status json_rpc = dumps(response, cls=json_encoder)
def dispatch(self, request, method="", json_encoder=None): from django.http import HttpResponse json_encoder = json_encoder or self.json_encoder try: # in case we do something json doesn't like, we always get back valid json-rpc response response = self.empty_response() if request.method.lower() == "get": valid, D = self.validate_get(request, method) if not valid: raise InvalidRequestError("The method you are trying to access is " "not availble by GET requests") elif not request.method.lower() == "post": raise RequestPostError else: try: D = loads(request.raw_post_data) except: raise InvalidRequestError if type(D) is list: response = [self.response_dict(request, d, is_batch=True, json_encoder=json_encoder)[0] for d in D] status = 200 else: response, status = self.response_dict(request, D, json_encoder=json_encoder) if response is None and (not u"id" in D or D[u"id"] is None): # a notification return HttpResponse("", status=status) json_rpc = dumps(response, cls=json_encoder) except Error, e: response["error"] = e.json_rpc_format status = e.status json_rpc = dumps(response, cls=json_encoder)
def dispatch(self, request, method='', json_encoder=None): if request.method.lower() == "options": return self.preflight(request) json_encoder = json_encoder or self.json_encoder try: # in case we do something json doesn't like, we always get back valid json-rpc response response = self.empty_response() if request.method.lower() == 'get': jsonrpc_request = self.validate_get(request, method) elif not request.method.lower() == 'post': raise RequestPostError else: try: jsonrpc_request = loads(request.raw_post_data) except: raise InvalidRequestError if type(jsonrpc_request) is list: response = [self.response_dict(request, d, is_batch=True, json_encoder=json_encoder)[0] for d in jsonrpc_request] status = 200 else: response, status = self.response_dict(request, jsonrpc_request, json_encoder=json_encoder) if response is None and (not u'id' in jsonrpc_request or jsonrpc_request[u'id'] is None): # a notification return HttpResponse('', status=status) json_rpc = dumps(response, cls=json_encoder) except Error, e: signals.got_request_exception.send(sender=self.__class__, request=request) response['error'] = e.json_rpc_format status = e.status json_rpc = dumps(response, cls=json_encoder)
def dispatch(self, request, method='', json_encoder=None): from django.http import HttpResponse json_encoder = json_encoder or self.json_encoder try: # in case we do something json doesn't like, we always get back valid json-rpc response response = self.empty_response() if request.method.lower() == 'get': valid, D = self.validate_get(request, method) if not valid: raise InvalidRequestError('The method you are trying to access is ' 'not available by GET requests') elif not request.method.lower() == 'post': raise RequestPostError else: try: D = loads(request.raw_post_data) except: raise InvalidRequestError if type(D) is list: response = [self.response_dict(request, d, is_batch=True, json_encoder=json_encoder)[0] for d in D] status = 200 else: response, status = self.response_dict(request, D, json_encoder=json_encoder) if response is None and (not u'id' in D or D[u'id'] is None): # a notification return HttpResponse('', status=status) json_rpc = dumps(response, cls=json_encoder) except Error, e: signals.got_request_exception.send(sender=self.__class__, request=request) response['error'] = e.json_rpc_format status = e.status json_rpc = dumps(response, cls=json_encoder)
def dispatch(self, request, method='', json_encoder=None): from django.http import HttpResponse json_encoder = json_encoder or self.json_encoder try: # in case we do something json doesn't like, we always get back valid json-rpc response response = self.empty_response() if request.method.lower() == 'get': valid, D = self.validate_get(request, method) if not valid: raise InvalidRequestError( 'The method you are trying to access is ' 'not available by GET requests') elif not request.method.lower() == 'post': raise RequestPostError else: try: if hasattr(request, "body"): D = loads(request.body.decode('utf-8')) else: D = loads(request.raw_post_data.decode('utf-8')) except: raise InvalidRequestError if type(D) is list: response = [self.response_dict(request, d, is_batch=True, json_encoder=json_encoder)[0] for d in D] status = 200 else: response, status = self.response_dict( request, D, json_encoder=json_encoder) if response is None and (not 'id' in D or D['id'] is None): # a notification return HttpResponse('', status=status) json_rpc = dumps(response, cls=json_encoder) except Error as e: signals.got_request_exception.send(sender=self.__class__, request=request) response['error'] = e.json_rpc_format status = e.status json_rpc = dumps(response, cls=json_encoder) except Exception as e: # exception missed by others signals.got_request_exception.send(sender=self.__class__, request=request) other_error = OtherError(e) response['result'] = None response['error'] = other_error.json_rpc_format status = other_error.status json_rpc = dumps(response, cls=json_encoder) return HttpResponse(json_rpc, status=status, content_type='application/json-rpc')
def dispatch(self, request, method="", json_encoder=None): from django.http import HttpResponse json_encoder = json_encoder or self.json_encoder try: # in case we do something json doesn't like, we always get back valid json-rpc response response = self.empty_response() if request.method.lower() == "get": valid, D = self.validate_get(request, method) if not valid: raise InvalidRequestError("The method you are trying to access is " "not available by GET requests") elif not request.method.lower() == "post": raise RequestPostError else: try: if hasattr(request, "body"): D = loads(request.body.decode("utf-8")) else: D = loads(request.raw_post_data.decode("utf-8")) except: raise InvalidRequestError if type(D) is list: response = [self.response_dict(request, d, is_batch=True, json_encoder=json_encoder)[0] for d in D] status = 200 else: response, status = self.response_dict(request, D, json_encoder=json_encoder) if response is None and (not "id" in D or D["id"] is None): # a notification return HttpResponse("", status=status) json_rpc = dumps(response, cls=json_encoder) except Error as e: response["error"] = e.json_rpc_format status = e.status json_rpc = dumps(response, cls=json_encoder) except Exception as e: # exception missed by others signals.got_request_exception.send(sender=self.__class__, request=request) # Put stacktrace into the OtherError only if DEBUG is enabled if settings.DEBUG: other_error = OtherError(e) else: other_error = OtherError("Internal Server Error") response["result"] = None response["error"] = other_error.json_rpc_format status = other_error.status json_rpc = dumps(response, cls=json_encoder) return HttpResponse(json_rpc, status=status, content_type="application/json-rpc")
def send_payload(self, params): """Performs the actual sending action and returns the result""" data = dumps({ 'jsonrpc': self.version, 'method': self.service_name, 'params': params, 'id': str(uuid.uuid1()) }).encode('utf-8') headers = { 'Content-Type': 'application/json-rpc', 'Accept': 'application/json-rpc', 'Content-Length': len(data) } try: req = urllib_request.Request(self.service_url, data, headers) resp = urllib_request.urlopen(req) except IOError as e: if isinstance(e, urllib_error.HTTPError): if e.code not in ( 401, 403 ) and e.headers['Content-Type'] == 'application/json-rpc': return e.read().decode( 'utf-8') # we got a jsonrpc-formatted respnose raise ServiceProxyException(e.code, e.headers, req) else: raise e return resp.read().decode('utf-8')
def send_payload(self, params): """Performs the actual sending action and returns the result""" data = dumps({ 'jsonrpc': self.version, 'method': self.service_name, 'params': params, 'id': str(uuid.uuid1()) }).encode('utf-8') headers = { 'Content-Type': 'application/json-rpc', 'Accept': 'application/json-rpc', 'Content-Length': len(data) } try: req = urllib_request.Request(self.service_url, data, headers) resp = urllib_request.urlopen(req) except IOError as e: if isinstance(e, urllib_error.HTTPError): if e.code not in ( 401, 403 ) and e.headers['Content-Type'] == 'application/json-rpc': return e.read().decode('utf-8') # we got a jsonrpc-formatted respnose raise ServiceProxyException(e.code, e.headers, req) else: raise e return resp.read().decode('utf-8')
def dont__call__(self, *args, **kwargs): params = kwargs if len(kwargs) else args if Any.kind(params) == Object and self.__version != '2.0': raise Exception('Unsupport arg type for JSON-RPC 1.0 ' '(the default version for this client, ' 'pass version="2.0" to use keyword arguments)') conn = httplib.HTTPSConnection ('localhost:8000') # self.__service_url) conn.request("POST", "/json/", # params, headers urllib.urlencode (dict (data = dumps({ "jsonrpc": self.__version, "method": self.__service_name, 'params': params, 'id': str(uuid.uuid1())}))), {}) response = conn.getresponse() print response.status, response.reason data = response.read() conn.close() y = loads(data) if u'error' in y: try: from django.conf import settings if settings.DEBUG: print '%s error %r' % (self.__service_name, y) except: pass return y
def __call__(self, *args, **kwargs): r = urllib.urlopen(self.__service_url, dumps({ "jsonrpc": self.__version, "method": self.__service_name, 'params': (args if args else kwargs), 'id': str(uuid.uuid1())})).read() return loads(r)
def send_payload(self, params): """Performs the actual sending action and returns the result""" return urllib.urlopen(self.service_url, dumps({ "jsonrpc": self.version, "method": self.service_name, 'params': params, 'id': str(uuid.uuid1())})).read()
def test_20_notify(self): req = { 'jsonrpc': '2.0', 'method': 'jsonrpc.notify', 'params': ['this is a string'], 'id': None } resp = urllib_request.urlopen(self.host, dumps(req).encode('utf-8')).read().decode('utf-8') self.assertEquals(resp, '')
def test_20_notify(self): req = { 'jsonrpc': '2.0', 'method': 'jsonrpc.notify', 'params': ['this is a string'], 'id': None } resp = urllib_request.urlopen(self.host, dumps(req).encode('utf-8')).read().decode('utf-8') self.assertEqual(resp, '')
def send_payload(self, params): """Performs the actual sending action and returns the result""" return requests.post( self.service_url, data=dumps({ "jsonrpc": self.version, "method": self.service_name, 'params': params, 'id': str(uuid.uuid1())})).json()
def test_20_notify(self): req = { u'jsonrpc': u'2.0', u'method': u'jsonrpc.notify', u'params': [u'this is a string'], u'id': None } resp = urllib.urlopen(self.host, dumps(req)).read() self.assertEquals(resp, '')
def __call__(self, *args, **kwargs): r = urllib.urlopen( self.__service_url, dumps({ "jsonrpc": self.__version, "method": self.__service_name, 'params': (args if args else kwargs), 'id': str(uuid.uuid1()) })).read() return loads(r)
def dispatch(self, request, method='', json_encoder=None): if request.method.lower() == "options": return self.preflight(request) json_encoder = json_encoder or self.json_encoder try: # in case we do something json doesn't like, we always get back valid json-rpc response response = self.empty_response() if request.method.lower() == 'get': jsonrpc_request = self.validate_get(request, method) elif not request.method.lower() == 'post': raise RequestPostError else: try: jsonrpc_request = loads(request.raw_post_data) except: raise InvalidRequestError if type(jsonrpc_request) is list: response = [ self.response_dict(request, d, is_batch=True, json_encoder=json_encoder)[0] for d in jsonrpc_request ] status = 200 else: response, status = self.response_dict( request, jsonrpc_request, json_encoder=json_encoder) if response is None and ( not u'id' in jsonrpc_request or jsonrpc_request[u'id'] is None): # a notification return HttpResponse('', status=status) json_rpc = dumps(response, cls=json_encoder) except Error, e: signals.got_request_exception.send(sender=self.__class__, request=request) response['error'] = e.json_rpc_format status = e.status json_rpc = dumps(response, cls=json_encoder)
def send_payload(self, params): dump = dumps({"jsonrpc" : self.version, "method" : self.service_name, "params" : params, "id" : str(uuid.uuid1()) }) dump_payload = FakePayload(dump) response = self.client.post(self.service_url, **{"wsgi.input" : dump_payload, 'CONTENT_LENGTH' : len(dump)}) return response.content
def test_20_batch(self): req = [{ 'jsonrpc': '2.0', 'method': 'jsonrpc.test', 'params': ['this is a string'], 'id': 'id-'+str(i) } for i in range(5)] resp = loads(urllib_request.urlopen(self.host, dumps(req).encode('utf-8')).read().decode('utf-8')) self.assertEquals(len(resp), len(req)) for i, D in enumerate(resp): self.assertEquals(D['result'], req[i]['params'][0]) self.assertEquals(D['id'], req[i]['id'])
def test_20_batch(self): req = [{ u'jsonrpc': u'2.0', u'method': u'jsonrpc.test', u'params': [u'this is a string'], u'id': u'id-'+unicode(i) } for i in range(5)] resp = loads(urllib.urlopen(self.host, dumps(req)).read()) self.assertEquals(len(resp), len(req)) for i, D in enumerate(resp): self.assertEquals(D[u'result'], req[i][u'params'][0]) self.assertEquals(D[u'id'], req[i][u'id'])
def test_20_batch(self): req = [{ 'jsonrpc': '2.0', 'method': 'jsonrpc.test', 'params': ['this is a string'], 'id': 'id-'+str(i) } for i in range(5)] resp = loads(urllib_request.urlopen(self.host, dumps(req).encode('utf-8')).read().decode('utf-8')) self.assertEqual(len(resp), len(req)) for i, D in enumerate(resp): self.assertEqual(D['result'], req[i]['params'][0]) self.assertEqual(D['id'], req[i]['id'])
def browse(request): if (request.GET.get('f', None) == 'mochikit.js'): return HttpResponse(mochikit.mochikit, content_type='application/x-javascript') if (request.GET.get('f', None) == 'interpreter.js'): return HttpResponse(mochikit.interpreter, content_type='application/x-javascript') desc = jsonrpc_site.service_desc() return render_to_response('browse.html', { 'methods': desc['procs'], 'method_names_str': dumps( [m['name'] for m in desc['procs']]) })
def browse(request): if request.GET.get('f', None) == 'mochikit.js': return HttpResponse(mochikit.mochikit, content_type='application/x-javascript') if request.GET.get('f', None) == 'interpreter.js': return HttpResponse(mochikit.interpreter, content_type='application/x-javascript') desc = jsonrpc_site.service_desc() return render_to_response('browse.html', { 'methods': desc['procs'], 'method_names_str': dumps( [m['name'] for m in desc['procs']]) })
def __call__(self, *args, **kwargs): params = kwargs if len(kwargs) else args if Any.kind(params) == Object and self.__version != '2.0': raise Exception('Unsupport arg type for JSON-RPC 1.0 ' '(the default version for this client, ' 'pass version="2.0" to use keyword arguments)') r = urllib.urlopen(self.__service_url, dumps({ "jsonrpc": self.__version, "method": self.__service_name, 'params': params, 'id': str(uuid.uuid1())})).read() return loads(r)
def send_payload(self, params): json_data = dumps({ 'jsonrpc': self.version, 'method': self.service_name, 'params': params, 'id': str(uuid.uuid1()) }) json_payload = FakePayload(json_data) client_args = { 'wsgi.input': json_payload, 'CONTENT_LENGTH': len(json_data) } response = self.client.post(self.service_url, **client_args) return response.content.decode('utf-8')
def send_payload(self, params): json_data = dumps({ 'jsonrpc': self.version, 'method': self.service_name, 'params': params, 'id': str(uuid.uuid1()) }) json_payload = FakePayload(json_data) client_args = { 'wsgi.input': json_payload, 'CONTENT_LENGTH': len(json_data) } response = self.client.post(self.service_url, **client_args) return response.content
def send_payload(self, params): """Performs the actual sending action and returns the result""" data = dumps({ "jsonrpc": self.version, "method": self.service_name, 'params': params, 'id': str(uuid.uuid1()), }) request = urllib2.Request(self.service_url, data=data, headers={ 'Accept': 'application/json', 'Content-Type': 'application/json', }) opener = urllib2.build_opener() return opener.open(request).read()
def test_20_batch_with_errors(self): req = [{ u'jsonrpc': u'2.0', u'method': u'jsonrpc.test' if not i % 2 else u'jsonrpc.fails', u'params': [u'this is a string'], u'id': u'id-' + unicode(i) } for i in range(10)] resp = loads(urllib2.urlopen(self.host, dumps(req)).read()) self.assertEquals(len(resp), len(req)) for i, D in enumerate(resp): if not i % 2: self.assertEquals(D[u'result'], req[i][u'params'][0]) self.assertEquals(D[u'id'], req[i][u'id']) else: self.assertEquals(D[u'result'], None) self.assert_(u'error' in D) self.assertEquals(D[u'error'][u'code'], 500)
def test_20_batch_with_errors(self): req = [{ u'jsonrpc': u'2.0', u'method': u'jsonrpc.test' if not i % 2 else u'jsonrpc.fails', u'params': [u'this is a string'], u'id': u'id-'+unicode(i) } for i in range(10)] resp = loads(urllib.urlopen(self.host, dumps(req)).read()) self.assertEquals(len(resp), len(req)) for i, D in enumerate(resp): if not i % 2: self.assertEquals(D[u'result'], req[i][u'params'][0]) self.assertEquals(D[u'id'], req[i][u'id']) else: self.assertEquals(D[u'result'], None) self.assert_(u'error' in D) self.assertEquals(D[u'error'][u'code'], 500)
def test_20_batch_with_errors(self): req = [{ 'jsonrpc': '2.0', 'method': 'jsonrpc.test' if not i % 2 else 'jsonrpc.fails', 'params': ['this is a string'], 'id': 'id-'+str(i) } for i in range(10)] resp = loads(urllib_request.urlopen(self.host, dumps(req).encode('utf-8')).read().decode('utf-8')) self.assertEqual(len(resp), len(req)) for i, D in enumerate(resp): if not i % 2: self.assertEqual(D['result'], req[i]['params'][0]) self.assertEqual(D['id'], req[i]['id']) self.assertTrue('error' not in D) else: self.assertTrue('result' not in D) self.assertTrue('error' in D) self.assertEqual(D['error']['code'], 500)
def test_20_batch_with_errors(self): req = [{ 'jsonrpc': '2.0', 'method': 'jsonrpc.test' if not i % 2 else 'jsonrpc.fails', 'params': ['this is a string'], 'id': 'id-'+str(i) } for i in range(10)] resp = loads(urllib_request.urlopen(self.host, dumps(req).encode('utf-8')).read().decode('utf-8')) self.assertEquals(len(resp), len(req)) for i, D in enumerate(resp): if not i % 2: self.assertEquals(D['result'], req[i]['params'][0]) self.assertEquals(D['id'], req[i]['id']) self.assert_('error' not in D) else: self.assert_('result' not in D) self.assert_('error' in D) self.assertEquals(D['error']['code'], 500)
def __call__(self, *args, **kwargs): params = kwargs if len(kwargs) else args if Any.kind(params) == Object and self.__version != '2.0': raise ValueError('Unsupported arg type for JSON-RPC 1.0 ' \ '(the default version for this client, ' \ 'pass version="2.0" to use keyword arguments)') response = self.client.post(self.__service_url, dumps({ "jsonrpc": self.__version, "method": self.__service_name, 'params': params, 'id': str(uuid.uuid1()), }), content_type="application/json-rpc") y = loads(response.content) if y.get("error", None): try: from django.conf import settings if settings.DEBUG: print '%s error %r' % (self.__service_name, y) except: pass return y
def __call__(self, *args, **kwargs): params = kwargs if len(kwargs) else args if Any.kind(params) == Object and self.__version != '2.0': raise Exception('Unsupport arg type for JSON-RPC 1.0 ' '(the default version for this client, ' 'pass version="2.0" to use keyword arguments)') # req = urllib2.Request(self.__service_url, ) r = urllib.urlopen(self.__service_url, dumps({ "jsonrpc": self.__version, "method": self.__service_name, 'params': params, 'id': str(uuid.uuid1())})).read() y = loads(r) if u'error' in y: try: from django.conf import settings if settings.DEBUG: print '%s error %r' % (self.__service_name, y) except: pass return y
def __call__(self, *args, **kwargs): if len(kwargs): params = kwargs else: params = args #if Any.kind(params) == Object and self.__version != '2.0': # raise Exception('Unsupport arg type for JSON-RPC 1.0 ' # '(the default version for this client, ' # 'pass version="2.0" to use keyword arguments)') # req = urllib2.Request(self.__service_url, ) r = urllib2.urlopen(self.__service_url, dumps({ "jsonrpc": self.__version, "method": self.__service_name, 'params': params, 'id': str(random.randint(10000, 100000000))}), 15).read() y = loads(r) if u'error' in y: pass return y
def __call__(self, *args, **kwargs): params = kwargs if len(kwargs) else args if Any.kind(params) == Object and self.__version != '2.0': raise Exception('Unsupport arg type for JSON-RPC 1.0 ' '(the default version for this client, ' 'pass version="2.0" to use keyword arguments)') req = urllib2.Request(self.__service_url, #r = urllib.urlopen(self.__service_url, data = dumps({ "jsonrpc": self.__version, "method": self.__service_name, 'params': params, 'id': str(uuid.uuid1())})) #.read() #r = urllib2.urlopen(req).read() opener = urllib2.build_opener (urllib2.HTTPSHandler(1)) f = opener.open (req) print 'READ', f, f.fp, print f.fp._sock, dir (f.fp._sock) #print req.has_data() #print req.get_data() print f.info() # same as f.fp._sock.msg - just the headers print f.fp._sock.status, f.fp._sock.reason, f.fp._sock.will_close, f.fp._sock.length print f.fp._sock.chunked, f.fp._sock.chunk_left, f.fp._sock.version #print f.fp._sock.read(1000) #print 'READ2' r = f.read() y = loads(r) if u'error' in y: try: from django.conf import settings if settings.DEBUG: print '%s error %r' % (self.__service_name, y) except: pass return y
def __call__(self, *args, **kwargs): params = kwargs if len(kwargs) else args if Any.kind(params) == Object and self.__version != '2.0': raise Exception('Unsupport arg type for JSON-RPC 1.0 ' '(the default version for this client, ' 'pass version="2.0" to use keyword arguments)') # req = urllib2.Request(self.__service_url, ) r = urllib.urlopen( self.__service_url, dumps({ "jsonrpc": self.__version, "method": self.__service_name, 'params': params, 'id': str(uuid.uuid1()) })).read() y = loads(r) if u'error' in y: try: from django.conf import settings if settings.DEBUG: print '%s error %r' % (self.__service_name, y) except: pass return y
json_rpc = dumps(response, cls=json_encoder) except Error, e: signals.got_request_exception.send(sender=self.__class__, request=request) response['error'] = e.json_rpc_format status = e.status json_rpc = dumps(response, cls=json_encoder) except Exception, e: # exception missed by others signals.got_request_exception.send(sender=self.__class__, request=request) other_error = OtherError(e) response['result'] = None response['error'] = other_error.json_rpc_format status = other_error.status json_rpc = dumps(response,cls=json_encoder) http = HttpResponse(json_rpc, status=status, content_type='application/json-rpc') http['Access-Control-Allow-Origin'] = "*" http['Access-Control-Allow-Headers'] = "Authorization" return http def procedure_desc(self, key): M = self.urls[key] return { 'name': M.json_method, 'summary': M.__doc__, 'idempotent': M.json_safe, 'params': [{'type': str(Any.kind(t)), 'name': k} for k, t in M.json_arg_types.iteritems()], 'return': {'type': M.json_return_type}}
def _call(host, req): return loads(urllib_request.urlopen(host, dumps(req).encode('utf-8')).read().decode('utf-8'))
def _call(self, req, path="/rpc/jukebox"): resp = loads( self.client.post(path, dumps(req), content_type="application/json").content) self.assert_("result" in resp.keys(), resp) return resp["result"]
def _call(host, req): return loads(urllib.urlopen(host, dumps(req)).read())
def _call(host, req): return loads( urllib_request.urlopen( host, dumps(req).encode('utf-8')).read().decode('utf-8'))
def _call(self, req, path="/rpc/jukebox"): resp = loads(self.client.post(path, dumps(req), content_type="application/json").content) self.assert_("result" in resp.keys(), resp) return resp["result"]
D[u'id'] is None): # a notification return HttpResponse('', status=status) json_rpc = dumps(response, cls=DjangoJSONEncoder) except Error, e: response['error'] = e.json_rpc_format status = e.status json_rpc = dumps(response, cls=DjangoJSONEncoder) except Exception, e: # exception missed by others other_error = OtherError(e) response['result'] = None response['error'] = other_error.json_rpc_format status = other_error.status json_rpc = dumps(response, cls=DjangoJSONEncoder) return HttpResponse(json_rpc, status=status, content_type='application/json-rpc') def procedure_desc(self, key): M = self.urls[key] return { 'name': M.json_method, 'summary': M.__doc__, 'idempotent': M.json_safe, 'params': M.json_args, 'return': { 'type': M.json_return_type }
except Error, e: signals.got_request_exception.send(sender=self.__class__, request=request) response['error'] = e.json_rpc_format status = e.status json_rpc = dumps(response, cls=json_encoder) except Exception, e: # exception missed by others signals.got_request_exception.send(sender=self.__class__, request=request) other_error = OtherError(e) response['result'] = None response['error'] = other_error.json_rpc_format status = other_error.status json_rpc = dumps(response, cls=json_encoder) response = HttpResponse(json_rpc, status=status, content_type='application/json-rpc') response["Access-Control-Allow-Origin"] = "*" return response def procedure_desc(self, key): M = self._urls[key] return { 'name': M.signature_data["method_name"], 'summary': M.__doc__, 'idempotent':
def __call__(self, *args, **kwargs): params = kwargs if len(kwargs) else args if Any.kind(params) == Object and self.__version not in ['2.0']: raise Exception('Unsupport arg type for JSON-RPC 1.0 ' '(the default version for this client, ' 'pass version="2.0" to use keyword arguments)') # req = urllib2.Request(self.__service_url, ) try: # 1. Prepare data url = self.__service_url data = dumps({ "jsonrpc": self.__version, "method": self.__service_name, 'params': params, 'id': str(uuid.uuid1())}) # 2. Sign it if self.__secret!=None: secret_key = callable(self.__secret) and self.__secret or self.__secret try: from hashlib import md5 except ImportError: from md5 import md5 import urlparse from urllib import urlencode hash_code = md5(data+secret_key).hexdigest() url = list(urlparse.urlparse(url)) params = dict([part.split('=') for part in url[4].split('&') if '&' in url[4]]) params['hash_code'] = hash_code url[4] = urlencode(params) url = urlparse.urlunparse(url) # 3. Invoke RPC method if url.startswith('http://testserver/'): # 3.1 Using Django test client url = url.partition('http://testserver')[-1] from django.test import Client c = Client() r = c.post(url, content_type='application/x-www-form-urlencoded',data=data).content else: # 3.2 Using real HTTP connection if self.__timeout and urllib2.__name__ == 'urllib2': # Timeout is provided r = urllib2.urlopen(url, data, timeout=self.__timeout).read() else: # Timeout not provied, or not supported r = urllib2.urlopen(url, data).read() # 4. Load JSON y = loads(r) except HTTPError, e: r = None try: r = e.fp.read() y = loads(r) except Exception, e1: if r: raise Exception(r[:2000]) raise e
def dispatch(self, request, method='', json_encoder=None): """ dispatch method for registering apps :param request: Request to process :param method: type of method :param json_encoder: json encdoer :return: response """ from django.http import HttpResponse json_encoder = json_encoder or self.json_encoder try: response = self._empty_response() if request.method.upper() == 'GET': is_valid, data = self._validate_get(request, method) if not is_valid: raise InvalidRequestError("The method you are trying to " "access is not available by GET " "requests") elif not request.method.upper() == 'POST': raise RequestPostError else: try: if hasattr(request, "body"): data = loads(request.body.decode('utf-8')) else: data = loads(request.raw_post_data.decode('utf-8')) except: raise InvalidRequestError if isinstance(data, list): response = [ self._response_dict(request, data=d, is_batch=True, json_encoder=json_encoder)[0] for d in data ] status = 200 else: response, status = self._response_dict( request, data, json_encoder=json_encoder) if response is None and not data.get('id'): return HttpResponse('', status=status) json_rpc = dumps(response, cls=json_encoder) except Error as e: response['error'] = e.json_rpc_format status = e.status json_rpc = dumps(response, cls=json_encoder) except Exception as e: # exception missed by others signals.got_request_exception.send(sender=self.__class__, request=request) # Put stacktrace into the OtherError only if DEBUG is enabled if settings.DEBUG: other_error = OtherError(e) else: other_error = OtherError("Internal Server Error") response['result'] = None response['error'] = other_error.json_rpc_format status = other_error.status json_rpc = dumps(response, cls=json_encoder) return HttpResponse(json_rpc, status=status, content_type='application/json-rpc')