Пример #1
0
    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 exceptions.InvalidRequestError('The method you are trying to access is not available by GET requests')
            elif not request.method.lower() == 'post':
                raise exceptions.RequestPostError
            else:
                if hasattr(request, "body"):
                    D = loads(request.body)
                else:
                    D = loads(request.raw_post_data)
            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 exceptions.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)
Пример #2
0
Файл: site.py Проект: lshift/nih
    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')
Пример #3
0
    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')
Пример #4
0
    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")
Пример #5
0
    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)
Пример #6
0
    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)
Пример #7
0
    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)
Пример #8
0
 def dispatch(self, request, method=''):      
   from django.core.serializers.json import DjangoJSONEncoder
   
   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)[0] for d in D]
       status = 200
     else:
       response, status = self.response_dict(request, D)
       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=DjangoJSONEncoder)
   except Error, e:
     response['error'] = e.json_rpc_format
     status = e.status
     json_rpc = dumps(response, cls=DjangoJSONEncoder)
Пример #9
0
  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
Пример #10
0
 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)
Пример #11
0
 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)
Пример #12
0
 def test_11_GET_mixed_args(self):
   params = {u'1': u'this is a string', u'2': u'this is omg', 
             u'wtf': u'pants', u'nowai': 'nopants'}
   url = "%s%s?%s" % (
     self.host, 'jsonrpc.strangeSafeEcho',
     (''.join(['%s=%s&' % (k, urllib.quote(v)) for k, v in params.iteritems()])).rstrip('&')
   )
   resp = loads(urllib.urlopen(url).read())
   self.assertEquals(resp[u'result'][-1], u'Default')
   self.assertEquals(resp[u'result'][1], u'this is omg')
   self.assertEquals(resp[u'result'][0], u'this is a string')
   self.assert_(u'error' not in resp)
Пример #13
0
 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'])
Пример #14
0
 def test_11_GET_mixed_args(self):
     params = {'1': 'this is a string', '2': 'this is omg',
               'wtf': 'pants', 'nowai': 'nopants'}
     url = "%s%s?%s" % (
         self.host, 'jsonrpc.strangeSafeEcho',
         (''.join(['%s=%s&' % (k, urllib_parse.quote(v)) for k, v in params.items()])).rstrip('&')
     )
     resp = loads(urllib_request.urlopen(url).read().decode('utf-8'))
     self.assertEqual(resp['result'][-1], 'Default')
     self.assertEqual(resp['result'][1], 'this is omg')
     self.assertEqual(resp['result'][0], 'this is a string')
     self.assertTrue('error' not in resp)
Пример #15
0
 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'])
Пример #16
0
 def test_11_GET_mixed_args(self):
   params = {'1': 'this is a string', '2': 'this is omg',
             'wtf': 'pants', 'nowai': 'nopants'}
   url = "%s%s?%s" % (
     self.host, 'jsonrpc.strangeSafeEcho',
     (''.join(['%s=%s&' % (k, urllib_parse.quote(v)) for k, v in params.items()])).rstrip('&')
   )
   resp = loads(urllib_request.urlopen(url).read().decode('utf-8'))
   self.assertEquals(resp['result'][-1], 'Default')
   self.assertEquals(resp['result'][1], 'this is omg')
   self.assertEquals(resp['result'][0], 'this is a string')
   self.assert_('error' not in resp)
Пример #17
0
 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'])
Пример #18
0
 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)
Пример #19
0
 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)
Пример #20
0
    def __call__(self, *args, **kwargs):
        params = kwargs if len(kwargs) else args
        if Any.kind(params) == Object and self.version != '2.0':
            raise Exception('Unsupported arg type for JSON-RPC 1.0 '
                            '(the default version for this client, '
                            'pass version="2.0" to use keyword arguments)')

        r = self.send_payload(params)
        y = loads(r)
        if 'error' in y:
            try:
                from django.conf import settings
                if settings.DEBUG:
                    print('JSONRPC: %s error %r' % (self.service_name, y))
            except:
                pass
        return y
Пример #21
0
  def __call__(self, *args, **kwargs):
    params = kwargs if len(kwargs) else args
    if Any.kind(params) == Object and self.version != '2.0':
      raise Exception('Unsupported arg type for JSON-RPC 1.0 '
                      '(the default version for this client, '
                      'pass version="2.0" to use keyword arguments)')

    r = self.send_payload(params)
    y = loads(r)
    if 'error' in y:
      try:
        from django.conf import settings
        if settings.DEBUG:
          print('JSONRPC: %s error %r' % (self.service_name, y))
      except:
        pass
    return y
Пример #22
0
 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)
Пример #23
0
 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)
Пример #24
0
 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)
Пример #25
0
    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)
Пример #26
0
  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:
          data = ''
          if request.META.get('HTTP_CONTENT_ENCODING','').lower() == 'gzip':
            compressed = cStringIO.StringIO(request.raw_post_data)
            data = gzip.GzipFile(fileobj=compressed).read()
          else:
            data = request.raw_post_data
  
          D = loads(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)
Пример #27
0
 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
Пример #28
0
 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
Пример #29
0
 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
Пример #30
0
 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
Пример #31
0
  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
Пример #32
0
def _call(host, req):
  return loads(urllib_request.urlopen(host, dumps(req).encode('utf-8')).read().decode('utf-8'))
Пример #33
0
  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
Пример #34
0
 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"]
Пример #35
0
    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')
Пример #36
0
 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"]
Пример #37
0
def _call(host, req):
  return loads(urllib.urlopen(host, dumps(req)).read())
Пример #38
0
def _call(host, req):
    return loads(
        urllib_request.urlopen(
            host,
            dumps(req).encode('utf-8')).read().decode('utf-8'))