Example #1
0
 def invoke(self,
            name,
            args=(),
            callback=None,
            onerror=None,
            byref=False,
            resultMode=HproseResultMode.Normal,
            simple=None):
     if simple == None: simple = self.simple
     if callback == None:
         return self.__invoke(name, args, byref, resultMode, simple)
     else:
         if isinstance(callback, str):
             callback = getattr(modules['__main__'], callback, None)
         if not hasattr(callback, '__call__'):
             raise HproseException("callback must be callable")
         if onerror == None:
             onerror = self.onError
         if onerror != None:
             if isinstance(onerror, str):
                 onerror = getattr(modules['__main__'], onerror, None)
             if not hasattr(onerror, '__call__'):
                 raise HproseException("onerror must be callable")
         threading.Thread(target=_AsyncInvoke(self.__invoke, name, args,
                                              callback, onerror, byref,
                                              resultMode, simple)).start()
Example #2
0
 def add(self, *args):
     args_num = len(args)
     if args_num == 1:
         if isinstance(args[0], (tuple, list)):
             self.addFunctions(args[0])
         elif isinstance(args[0], type):
             self.addClassMethods(args[0])
             self.addStaticMethods(args[0])
         elif hasattr(args[0], '__call__'):
             self.addFunction(args[0])
         else:
             self.addInstanceMethods(args[0])
     elif args_num == 2:
         if isinstance(args[0], type):
             if isinstance(args[1], type):
                 self.addClassMethods(args[0], args[1])
             else:
                 self.addClassMethods(args[0], args[0], args[1])
                 self.addStaticMethods(args[0], args[1])
         elif isinstance(args[0], str):
             if isinstance(args[1], str):
                 self.addFunction(args[0], args[1])
             else:
                 self.addMethod(args[0], args[1])
         elif isinstance(args[0], (tuple, list)):
             if isinstance(args[1], (tuple, list)):
                 self.addFunctions(args[0], args[1])
             else:
                 self.addMethods(args[0], args[1])
         elif hasattr(args[0], '__call__') and isinstance(args[1], str):
             self.addFunction(args[0], args[1])
         elif isinstance(args[1], str):
             self.addInstanceMethods(args[0], None, args[1])
         else:
             self.addInstanceMethods(args[0], args[1])
     elif args_num == 3:
         if isinstance(args[0], str) and isinstance(args[2], str):
             if args[1] == None:
                 self.addFunction(args[0], args[2])
             else:
                 self.addMethod(args[0], args[1], args[2])
         elif isinstance(args[0], (tuple, list)):
             if isinstance(args[2], (tuple, list)) and args[1] == None:
                 self.addFunctions(args[0], args[2])
             else:
                 self.addMethods(args[0], args[1], args[2])
         elif isinstance(args[1], type) and isinstance(args[2], str):
             if isinstance(args[0], type):
                 self.addClassMethods(args[0], args[1], args[2])
             else:
                 self.addInstanceMethods(args[0], args[1], args[2])
         elif hasattr(args[0],
                      '__call__') and args[1] == None and isinstance(
                          args[2], str):
             self.addFunction(args[0], args[2])
         else:
             raise HproseException('Wrong arguments')
     else:
         raise HproseException('Wrong arguments')
Example #3
0
 def unexpectedTag(self, tag, expectTags=None):
     if tag == b'':
         raise HproseException('No byte found in stream')
     elif expectTags == None:
         raise HproseException("Unexpected serialize tag '%s' in stream" %
                               str(tag, 'utf-8'))
     else:
         raise HproseException(
             "Tag '%s' expected, but '%s' found in stream" %
             (str(expectTags, 'utf-8'), str(tag, 'utf-8')))
Example #4
0
 def _sendAndReceive(self, data):
     header = {'Content-Type': 'application/hprose'}
     header['Host'] = self.__host
     if (self.__port != 80):
         header['Host'] += ':' + str(self.__port)
     cookie = _getCookie(self.__host, self.__path, self.__scheme == 'https')
     if cookie != '':
         header['Cookie'] = cookie
     if self.keepAlive:
         header['Connection'] = 'keep-alive'
         header['Keep-Alive'] = str(self.keepAliveTimeout)
     else:
         header['Connection'] = 'close'
     for name in self.__header:
         header[name] = self.__header[name]
     httpclient = self.__getconn()
     if self.__proxy == None:
         path = urllib.parse.urlunsplit(
             ('', '', self.__path, self.__query, self.__fragment))
     else:
         path = self._uri
     httpclient.request('POST', path, data, header)
     resp = httpclient.getresponse()
     if resp.status == 200:
         cookieList = resp.getheader('set-cookie', '').split(',')
         cookieList.extend(resp.getheader('set-cookie2', '').split(','))
         _setCookie(cookieList, self.__host)
         data = resp.read()
         if not self.keepAlive:
             httpclient.close()
         return data
     else:
         if not self.keepAlive:
             httpclient.close()
         raise HproseException('%d:%s' % (resp.status, resp.reason))
Example #5
0
 def serialize(self, v):
     if v == None: self.writeNull()
     elif isinstance(v, bool): self.writeBoolean(v)
     elif isinstance(v, int): self.writeInteger(v)
     elif isinstance(v, float): self.writeDouble(v)
     elif isinstance(v, decimal.Decimal): self.writeDouble(v)
     elif isinstance(v, (bytes, bytearray, memoryview)):
         self.writeBytesWithRef(v)
     elif isinstance(v, str):
         if v == '':
             self.writeEmpty()
         elif len(v) == 1:
             self.writeUTF8Char(v)
         else:
             self.writeStringWithRef(v)
     elif isinstance(v, UUID):
         self.writeGuidWithRef(v)
     elif isinstance(v, (list, tuple)):
         self.writeListWithRef(v)
     elif isinstance(v, (dict_items, dict_keys, dict_values)):
         self.writeViewWithRef(v)
     elif isinstance(v, dict):
         self.writeMapWithRef(v)
     elif isinstance(v, (datetime.datetime, datetime.date)):
         self.writeDateWithRef(v)
     elif isinstance(v, datetime.time):
         self.writeTimeWithRef(v)
     elif isinstance(v, object):
         self.writeObjectWithRef(v)
     else:
         raise HproseException('Not support to serialize this data')
Example #6
0
 def __doInput(self, data, args, resultMode):
     for _filter in reversed(self.__filters):
         data = _filter.inputFilter(data, self)
     if data == None or len(data) == 0 or data[len(data) -
                                               1:] != HproseTags.TagEnd:
         raise HproseException("Wrong Response: \r\n%s" %
                               str(data, 'utf-8'))
     if resultMode == HproseResultMode.RawWithEndTag:
         return data
     if resultMode == HproseResultMode.Raw:
         return data[:-1]
     stream = BytesIO(data)
     reader = HproseReader(stream)
     result = None
     try:
         error = None
         while True:
             tag = stream.read(1)
             if tag == HproseTags.TagEnd:
                 break
             elif tag == HproseTags.TagResult:
                 if resultMode == HproseResultMode.Normal:
                     reader.reset()
                     result = reader.unserialize()
                 else:
                     s = reader.readRaw()
                     result = s.getvalue()
                     s.close()
             elif tag == HproseTags.TagArgument:
                 reader.reset()
                 a = reader.readList()
                 if isinstance(args, list):
                     for i in range(len(args)):
                         args[i] = a[i]
             elif tag == HproseTags.TagError:
                 reader.reset()
                 error = reader.readString()
             else:
                 raise HproseException("Wrong Response: \r\n%s" %
                                       str(data, 'utf-8'))
         if error != None:
             raise HproseException(error)
     finally:
         stream.close()
     return result
Example #7
0
 def addFunctions(self,
                  functions,
                  aliases=None,
                  resultMode=HproseResultMode.Normal,
                  simple=None):
     aliases_is_null = (aliases == None)
     if not isinstance(functions, (list, tuple)):
         raise HproseException('Argument functions is not a list or tuple')
     count = len(functions)
     if not aliases_is_null and count != len(aliases):
         raise HproseException(
             'The count of functions is not matched with aliases')
     for i in range(count):
         function = functions[i]
         if aliases_is_null:
             self.addFunction(function, None, resultMode, simple)
         else:
             self.addFunction(function, aliases[i], resultMode, simple)
Example #8
0
 def addFunction(self,
                 function,
                 alias=None,
                 resultMode=HproseResultMode.Normal,
                 simple=None):
     if isinstance(function, str):
         function = getattr(modules['__main__'], function, None)
     if not hasattr(function, '__call__'):
         raise HproseException('Argument function is not callable')
     if alias == None:
         alias = function.__name__
     if isinstance(alias, str):
         aliasname = alias.lower()
         self.__functions[aliasname] = function
         self.__funcNames[aliasname] = alias
         self.__resultMode[aliasname] = resultMode
         self.__simpleMode[aliasname] = simple
     else:
         raise HproseException('Argument alias is not a string')
Example #9
0
 def __readUTF8CharWithoutTag(self):
     s = []
     c = self.stream.read(1)
     s.append(c)
     a = ord(c)
     if (a & 0xE0) == 0xC0:
         s.append(self.stream.read(1))
     elif (a & 0xF0) == 0xE0:
         s.append(self.stream.read(2))
     elif a > 0x7F:
         raise HproseException('Bad utf-8 encoding')
     return str(b''.join(s), 'utf-8')
Example #10
0
 def __readUTF8CharRaw(self, ostream):
     s = []
     c = self.stream.read(1)
     s.append(c)
     a = ord(c)
     if (a & 0xE0) == 0xC0:
         s.append(self.stream.read(1))
     elif (a & 0xF0) == 0xE0:
         s.append(self.stream.read(2))
     elif a > 0x7F:
         raise HproseException('Bad utf-8 encoding')
     ostream.write(b''.join(s))
Example #11
0
 def _doInvoke(self, istream, context):
     simpleReader = HproseReader(istream, True)
     tag = HproseTags.TagCall
     while tag == HproseTags.TagCall:
         name = simpleReader.readString()
         aliasname = name.lower()
         args = []
         byref = False
         tag = simpleReader.checkTags(
             (HproseTags.TagList, HproseTags.TagEnd, HproseTags.TagCall))
         if tag == HproseTags.TagList:
             reader = HproseReader(istream)
             args = reader.readListWithoutTag()
             tag = reader.checkTags((HproseTags.TagTrue, HproseTags.TagEnd,
                                     HproseTags.TagCall))
             if (tag == HproseTags.TagTrue):
                 byref = True
                 tag = reader.checkTags(
                     (HproseTags.TagEnd, HproseTags.TagCall))
         self._fireBeforeInvokeEvent(name, args, byref, context)
         if aliasname in self.__functions:
             function = self.__functions[aliasname]
             resultMode = self.__resultMode[aliasname]
             simple = self.__simpleMode[aliasname]
             result = function(*self._fixArgs(args, function, context))
         elif '*' in self.__functions:
             function = self.__functions['*']
             resultMode = self.__resultMode['*']
             simple = self.__simpleMode['*']
             result = function(name, args)
         else:
             raise HproseException("Can't find this function %s()." % name)
         self._fireAfterInvokeEvent(name, args, byref, result, context)
         ostream = BytesIO()
         if resultMode == HproseResultMode.RawWithEndTag:
             return self.__outputFilter(result, context)
         if resultMode == HproseResultMode.Raw:
             ostream.write(result)
         else:
             ostream.write(HproseTags.TagResult)
             if resultMode == HproseResultMode.Serialized:
                 ostream.write(result)
             else:
                 if simple == None: simple = self.simple
                 writer = HproseWriter(ostream, simple)
                 writer.serialize(result)
                 if byref:
                     ostream.write(HproseTags.TagArgument)
                     writer.reset()
                     writer.writeList(args)
     ostream.write(HproseTags.TagEnd)
     return self._responseEnd(ostream, context)
Example #12
0
 def addMethods(self,
                methods,
                belongto,
                aliases=None,
                resultMode=HproseResultMode.Normal,
                simple=None):
     aliases_is_null = (aliases == None)
     if not isinstance(methods, (list, tuple)):
         raise HproseException('Argument methods is not a list or tuple')
     if isinstance(aliases, str):
         aliasPrefix = aliases
         aliases = [aliasPrefix + '_' + name for name in methods]
     count = len(methods)
     if not aliases_is_null and count != len(aliases):
         raise HproseException(
             'The count of methods is not matched with aliases')
     for i in range(count):
         method = methods[i]
         function = getattr(belongto, method, None)
         if aliases_is_null:
             self.addFunction(function, method, resultMode, simple)
         else:
             self.addFunction(function, aliases[i], resultMode, simple)
Example #13
0
 def _handle(self, data, context):
     istream = None
     try:
         data = self.__inputFilter(data, context)
         if data == None or data == b'' or data[len(data) -
                                                1:] != HproseTags.TagEnd:
             raise HproseException("Wrong Request: \r\n%s" %
                                   str(data, 'utf-8'))
         istream = BytesIO(data)
         tag = istream.read(1)
         if tag == HproseTags.TagCall:
             return self._doInvoke(istream, context)
         elif tag == HproseTags.TagEnd:
             return self._doFunctionList(context)
         else:
             raise HproseException("Wrong Request: \r\n%s" %
                                   str(data, 'utf-8'))
     except (KeyboardInterrupt, SystemExit):
         raise
     except Exception as e:
         return self._doError(e, context)
     finally:
         if istream != None: istream.close()
Example #14
0
 def unserialize(self):
     tag = self.stream.read(1)
     if b'0' <= tag <= b'9':
         return int(tag, 10)
     if (tag == HproseTags.TagInteger or tag == HproseTags.TagLong):
         return self.__readIntegerWithoutTag()
     if tag == HproseTags.TagDouble:
         return self.__readDoubleWithoutTag()
     if tag == HproseTags.TagNull:
         return None
     if tag == HproseTags.TagEmpty:
         return ''
     if tag == HproseTags.TagTrue:
         return True
     if tag == HproseTags.TagFalse:
         return False
     if tag == HproseTags.TagNaN:
         return NaN
     if tag == HproseTags.TagInfinity:
         return self.__readInfinityWithoutTag()
     if tag == HproseTags.TagDate:
         return self.readDateWithoutTag()
     if tag == HproseTags.TagTime:
         return self.readTimeWithoutTag()
     if tag == HproseTags.TagBytes:
         return self.readBytesWithoutTag()
     if tag == HproseTags.TagUTF8Char:
         return self.__readUTF8CharWithoutTag()
     if tag == HproseTags.TagString:
         return self.readStringWithoutTag()
     if tag == HproseTags.TagGuid:
         return self.readGuidWithoutTag()
     if tag == HproseTags.TagList:
         return self.readListWithoutTag()
     if tag == HproseTags.TagMap:
         return self.readMapWithoutTag()
     if tag == HproseTags.TagClass:
         self.__readClass()
         return self.readObject()
     if tag == HproseTags.TagObject:
         return self.readObjectWithoutTag()
     if tag == HproseTags.TagRef:
         return self.__readRef()
     if tag == HproseTags.TagError:
         raise HproseException(self.readString())
     self.unexpectedTag(tag)
Example #15
0
 def read(self, index):
     raise HproseException("Unexpected serialize tag '%s' in stream" %
                           str(HproseTags.TagRef, 'utf-8'))