from message.api import MessageService
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer


class MessageServiceHandler:
    def sendMobileMessage(self, mobile, message):
        print("sendMobileMessage" + mobile + " message:" + message)
        return True


def sendEmailMessage(self, email, message):
    print("sendEmailMessage email:" + email + " message:" + message)

    return True


if __name__ == '__main__':
    handler = MessageServiceHandler()
    processor = MessageService.Processor(handler)
    transport = TSocket.TServerSocket("127.0.0.1", "9090")
    tfactory = TTransport.TFramedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()
    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
    print("pthon thrift server start")
    server.serve()
    print("python thrift server exit")
    server.serve()
    sys.exit(0)

# set up server transport and transport factory

rel_path = "../keys/server.pem"
abs_key_path = os.path.join(script_dir, rel_path)

host = None
if options.ssl:
    from thrift.transport import TSSLSocket
    transport = TSSLSocket.TSSLServerSocket(host,
                                            options.port,
                                            certfile=abs_key_path)
else:
    transport = TSocket.TServerSocket(host, options.port)
tfactory = TTransport.TBufferedTransportFactory()
if options.trans == 'buffered':
    tfactory = TTransport.TBufferedTransportFactory()
elif options.trans == 'framed':
    tfactory = TTransport.TFramedTransportFactory()
elif options.trans == '':
    raise AssertionError('Unknown --transport option: %s' % options.trans)
else:
    tfactory = TTransport.TBufferedTransportFactory()
# if --zlib, then wrap server transport, and use a different transport factory
if options.zlib:
    transport = TZlibTransport.TZlibTransport(transport)  # wrap  with zlib
    tfactory = TZlibTransport.TZlibTransportFactory()

# do server-specific setup here:
Example #3
0
                if val in res:
                    res.remove(val)
                else:
                    res.add(val)
            getAtCache.put(key, time, res)
            return res

    def delKey(self, key):
        store.delKey(key)

    def delVal(self, key, val):
        store.delVal(key, val)

    def diff(self, key, time1, time2):
        return store.diff(key, time1, time2)


PORT = 8081
handler = HSHandler()
processor = HistoryStore.Processor(handler)
transport = TSocket.TServerSocket(port=PORT)

tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

print "Starting python server..."
server.serve()
print "done!"
    def closeFinger(self, key):
        for x in range(255, -1, -1):
            if belongsTo(self.node_list[x].id, self.curr_node.id,
                         key) and self.node_list[x].id != self.curr_node.id:
                return self.node_list[x]
        return self.curr_node

    def getNodeSucc(self):
        if not self.node_list:
            s = SystemException()
            s.message = "Finger table does not exist"
            raise s
        node = self.node_list[0]
        return node


if __name__ == '__main__':
    handler = FileStoreHandler()
    processor = FileStore.Processor(handler)
    transport = TSocket.TServerSocket(port=int(sys.argv[1]))
    hostname = socket.gethostname()
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
    # You could do one of these for a multithreaded server
    # server = TServer.TThreadedServer(
    #	processor, transport, tfactory, pfactory)
    print('Starting the server...')
    server.serve()
Example #5
0
        self.log = {}
        self.client = MongoClient(mongo_server, mongo_port)
        self.db = self.client.thrift_kv_db
        self.collection = self.db.thrift_kv_collection

    def create(self, value):
        value = loads(value)
        return dumps(self.collection.insert_one(value).inserted_id)

    def read(self, obj_id):
        return dumps(self.collection.find_one({'_id' : loads(obj_id)}))

    def update(self, obj_id, value):
        obj_id = loads(obj_id)
        value = loads(value)
        ret = self.collection.find_one_and_replace({'_id': obj_id}, value,
                return_document=ReturnDocument.AFTER)
        return dumps(ret)

    def delete_doc(self, obj_id):
        self.collection.delete_one({'_id': loads(obj_id)})

if __name__ == "__main__":
    handler = ThriftKVHandler()
    processor = ThriftKVService.Processor(handler)
    transport = TSocket.TServerSocket(host='0.0.0.0', port=9090)
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()
    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
    server.serve()
Example #6
0
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

import mplayer_handler as m_handler
from lucidaservice import lucida_service

if __name__ == '__main__':
    handler = m_handler.MplayerHandler()
    processor = lucida_service.Processor(handler)
    transport = TSocket.TServerSocket(port=8088)
    tfactory = TTransport.TFramedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
    server.serve()
Example #7
0
from py.thrift.generated import PersonService
from PersonServiceImpl import PersonServiceImpl
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TCompactProtocol
from thrift.server import TServer

try:
    personServiceHandler = PersonServiceImpl()
    processor = PersonService.Processor(personServiceHandler)

    serverSocket = TSocket.TServerSocket(host="127.0.0.1", port=8899)
    transportFactory = TTransport.TFramedTransportFactory()
    protocolFactory = TCompactProtocol.TCompactProtocolFactory()

    server = TServer.TSimpleServer(processor, serverSocket, transportFactory, protocolFactory)
    print("Python Server Started!")
    server.serve()

except Thrift.TException as tx:
    print('%s' % tx.message)
Example #8
0
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

import handler
import conf
import logging

users = []

#set logging
logging.basicConfig(level=logging.INFO)

#read configure file
config = conf.load_config('conf/pyscribe.conf')

handler = handler.LogHandler()
#set parsers
handler.parsers = conf.get_parsers(config.items('parsers'))

processor = scribe.Processor(handler)
transport = TSocket.TServerSocket(config.getint('common', 'port'))
tfactory = TTransport.TFramedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

print 'Starting the server...'
server.serve()
print 'done.'
Example #9
0
# Apache Thrift Hello World Python Server

import sys
sys.path.append("gen-py")

from thrift.transport import TSocket
from thrift.server import TServer
from hello import HelloSvc


class HelloHandler:
    def hello_func(self):
        print("[Server] Handling client request")
        return "Hello thrift, from the python server"


handler = HelloHandler()
processor = HelloSvc.Processor(handler)
listeningSocket = TSocket.TServerSocket(port=8585)
server = TServer.TSimpleServer(processor, listeningSocket)

print("[Server] Started")
server.serve()
Example #10
0
from rpc import NewsServlet
from rpc.ttypes import *

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer


class NewsHandler:
    def __init__(self):
        pass

    def get_news_detail(self):
        print "client call %s" % (self.__class__.__name__)
        return NewsDetail(1, "title", "content", "news", str(time.time()))

    def get_news_list(self):
        pass


handler = NewsHandler()
processor = NewsServlet.Processor(handler)
transport = TSocket.TServerSocket(port=12345)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

server.serve()
Example #11
0
    def get_extraction(self, req):
        rsp = ExtRsp()
        rsp.text = req.text
        rsp.server_info = '47.94.210.236'
        #FIXME: 调用模型获取kn
        path = cur_path + '/out/1.txt'
        sentences = self.get_sentences(req.text)
        rsp.kn = self.handle(sentences, path)
        return rsp

    def set_badcase(self, req):
        return BadCaseRsp('ok', '47.94.210.236')


if __name__ == '__main__':
    handler = ExtractionHandler()

    processor = ExtractionService.Processor(handler)
    transport = TSocket.TServerSocket(__HOST, __PORT)
    # 传输方式,使用buffer
    tfactory = TTransport.TBufferedTransportFactory()
    # 传输的数据类型:二进制
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    # 创建一个thrift 服务
    rpcServer = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

    print('Starting the rpc server at', __HOST, ':', __PORT)
    rpcServer.serve()
    print('done')
Example #12
0
# -*- coding:utf-8 -*-
from thrift import Thrift
from py.thrift import PersonService
from thrift.transport import TTransport
from thrift.transport import TSocket
from thrift.protocol import TCompactProtocol
from thrift.server import TServer
from PersonServiceImpl import PsersonServiceImpl

try:
    personHandler = PsersonServiceImpl()
    processor = PersonService.Processor(personHandler)
    ss = TSocket.TServerSocket(port=8800, host="localhost")
    transFactory = TTransport.TFramedTransportFactory()
    protocolFactory = TCompactProtocol.TCompactProtocolFactory()

    server = TServer.TSimpleServer(processor, ss, transFactory,
                                   protocolFactory)
    server.serve()
except Thrift.TException as e:
    pass
Example #13
0
# Apache Thrift Frame Layer Network Transport Server in Python

from thrift.transport import TSocket
from thrift.transport import TTransport

acceptor = TSocket.TServerSocket(port=9090)
acceptor.listen();
print("[Server] listening on port 9090")

while (True):
    trans_ep = acceptor.accept();
    trans = TTransport.TFramedTransport(trans_ep)
    data = trans.read(1024*8)
    print("[Server] handling request: %s" % (data))
    trans.write("Hello Thrift!");
    trans.flush()
    trans.close() 
    if data[:4] == "STOP":
        break

print("[Server] exiting")
acceptor.close()

Example #14
0
    def sendEmailMessage(self, email, message):
        print("sendEmailMessage, email:" + email + ", message:" + message)
        messageObj = MIMEText(message, "plain", "utf-8")
        messageObj['From'] = sender
        messageObj['To'] = email
        messageObj['Subject'] = Header('709小骚骚代码测试邮件,勿慌', 'utf-8')
        try:
            smtpObj = smtplib.SMTP('smtp.163.com')
            smtpObj.login(sender, authCode)
            smtpObj.sendmail(sender, [email], messageObj.as_string())
            print("send mail success")
            return True
        except smtplib.SMTPException:
            print("send mail failed!")
            return False


if __name__ == '__main__':
    handler = MessageServiceHandler()
    processor = MessageService.Processor(handler)
    # transport = TSocket.TServerSocket(host="127.0.0.1", port = 9090)
    transport = TSocket.TServerSocket(host=None, port=9090)
    tfactory = TTransport.TFramedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
    print("python thrift server start")
    server.serve()
    print("python thrift server exit")
Example #15
0
class MyTestHandler:
    def __init__(self):
        self.log = {}

    def helloThrift(self):
        print "Hello Thrift!"

    def studyThrift(self):
        print "I'm studying Thrift!"
        return "I'm studying Thrift from " + socket.gethostbyname(
            socket.gethostname())

    def sayMsg(self, msg):
        print "sayMsg(" + msg + ")"
        return "say " + msg + " from " + socket.gethostbyname(
            socket.gethostname())


handler = MyTestHandler()
processor = MyTest.Processor(handler)
transport = TSocket.TServerSocket('127.0.0.1', 3333)
# 选择传输层
tfactory = TTransport.TBufferedTransportFactory()
# 选择传输协议
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
# 创建服务端
server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

print "Starting python server..."
server.serve()
Example #16
0
        log = SharedStruct()
        log.key = logid
        log.value = '%d' % (val)
        self.log[logid] = log

        return val

    def getStruct(self, key):
        print 'getStruct(%d)' % (key)
        return self.log[key]

    def zip(self):
        print 'zip()'


handler = CalculatorHandler()
processor = Calculator.Processor(handler)
transport = TSocket.TServerSocket(host='localhost', port=9090)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

# You could do one of these for a multithreaded server
#server = TServer.TThreadedServer(processor, transport, tfactory, pfactory)
#server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)

print 'Starting the server...'
server.serve()
print 'done.'
Example #17
0
    msgObj['Subject'] = Header('LeedCode Team Email', 'utf-8')
    # Setup smtp server and send out email
    # smtpserver = smtplib.SMTP_SSL("smtp.gmail.com", 465)
    # smtpserver.ehlo()
    # smtpserver.login(gmail_user, gmail_password)
    # smtpserver.sendmail(from_address, email, mail.as_string())
    # smtpserver.quit()
    try:
        smtp = smtplib.SMTP('smtp.gmail.com')
        smtp.login(gmail_user, gmail_password)
        smtp.sendmail(from_address, [email], msgObj.as_string())
        print("Send email succeed!")
        return True
    except smtplib.SMTPException as e:
        print("Send email failed! Error: " + e)
        return False


if __name__ == '__main__':
    port = 9090
    handler = MSGServiceHandler()
    processor = MSGService.Processor(handler)
    transport = TSocket.TServerSocket(None, port)
    tfactory = TTransport.TFramedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
    print("python thrift server start at :%d" % port)
    server.serve()
    print("python thrift server exit")
Example #18
0
            EntityMentionSet(uuid=aug.next(),
                             metadata=AnnotationMetadata(timestamp=int(
                                 time.time()),
                                                         tool="nltk"),
                             mentionList=sum(entities.values(), [])))

        return communication


if __name__ == "__main__":

    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("-p", "--port", dest="port", type=int, default=9090)
    options = parser.parse_args()

    logging.basicConfig(level=logging.INFO)

    handler = CommunicationHandler()
    processor = Annotator.Processor(handler)
    transport = TSocket.TServerSocket(port=options.port)
    tfactory = TTransport.TBufferedTransportFactory()
    ipfactory = TCompactProtocol.TCompactProtocolFactory()
    opfactory = TCompactProtocol.TCompactProtocolFactory()

    server = TNonblockingServer.TNonblockingServer(processor, transport,
                                                   ipfactory, opfactory)
    logging.info('Starting the server...')
    server.serve()
                if i.id > self.NodeID and i.id <= key:
                    t = TSocket.TSocket(i.ip, i.port)
                    t = TTransport.TBufferedTransport(t)
                    p = TBinaryProtocol.TBinaryProtocol(t)
                    c = FileStore.Client(p)
                    t.open()
                    k = c.findPred(key)
                    t.close()
                    return k
            raise SystemException("Find Pred Error - Cannot find pred 2")
            
    # NodeID getNodeSucc() 
    # throws (1: SystemException systemException),
    def getNodeSucc(self):
        if not len(self.finger_table):
            raise SystemException("Get Node Succ Error - Finger table is missing")
        return self.finger_table[0]

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    handler = ChordHandler()
    processor = FileStore.Processor(handler)
    transport = TSocket.TServerSocket(port=handler.port_num)
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()
    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

    print('Starting the server...')
    server.serve()
    print('done.')
def create_server():
    handler = WeatherPiThriftHandler()
    return TServer.TSimpleServer(GenericPiThriftService.Processor(handler),
                                 TSocket.TServerSocket(port=port),
                                 TTransport.TBufferedTransportFactory(),
                                 TBinaryProtocol.TBinaryProtocolFactory())
Example #21
0
    def __init__(self, processor, handler, config):
        self._logger = logging.getLogger(__name__)
        self._section_name = utils.get_module(__name__)
        self._server = None
        self._service_name = config.get(self._section_name,
                                        "service",
                                        required=True)
        self._port = config.getint(self._section_name, "port", required=True)
        self._zk_connect_str = config.get(self._section_name,
                                          "zk_connect_str",
                                          required=True)
        self._auth_user = config.get(self._section_name,
                                     "auth_user",
                                     required=True)
        self._auth_password = config.get(self._section_name,
                                         "auth_password",
                                         required=True)
        self._monitor = config.getboolean(self._section_name,
                                          "monitor",
                                          default=settings.SERVICE_MONITOR)
        self._c_module_serialize = config.getboolean(
            self._section_name,
            "c_module_serialize",
            default=settings.USE_C_MODULE_SERIALIZE)
        self._server_name = config.get(self._section_name, "name")
        self._owner = config.get(self._section_name, "owner")

        hosts = "%s/%s" % (self._zk_connect_str,
                           settings.DEFAULT_ZK_NAMESPACE_ROOT)

        self._server_path = "%s/%s" % (self._service_name,
                                       settings.DEFAULT_ZK_NAMESPACE_SERVERS)
        self._statistic_path = "%s/%s/%s" % (
            self._service_name, settings.DEFAULT_ZK_NAMESPACE_STATISTICS,
            settings.DEFAULT_ZK_NAMESPACE_SERVERS)
        # create zk acl
        self._acls = []
        self._acls.append(
            make_digest_acl(self._auth_user, self._auth_password, all=True))
        self._acls.append(make_acl("world", "anyone", read=True))
        # create zk_client
        self._zkclient = prpcZKClientManager.make(hosts, config, "server")
        self._zkclient.add_auth(
            "digest", "%s:%s" % (self._auth_user, self._auth_password))

        # create zkpath
        if not self._zkclient.exists(self._service_name):
            self._zkclient.create(self._service_name, makepath=True)
        if not self._zkclient.exists(self._server_path):
            self._zkclient.create(self._server_path, acl=self._acls)
        if not self._zkclient.exists(self._statistic_path):
            self._zkclient.create(self._statistic_path, makepath=True)

        self.transport = TSocket.TServerSocket(port=self._port)
        self.tfactory = TTransport.TBufferedTransportFactory()

        if self._monitor:
            self._collector = StatisticsCollector(self._zkclient,
                                                  config,
                                                  is_server=True)
            self._processor = self._statistics_wrapper(processor)(handler)
        else:
            self._processor = processor(handler)

        if self._c_module_serialize:
            self.pfactory = TBinaryProtocol.TBinaryProtocolAcceleratedFactory()
        else:
            self.pfactory = TBinaryProtocol.TBinaryProtocolFactory()
Example #22
0
thrift_client.py
"""
import socket
import sys
from inference import Inference
from inference.ttypes import *

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer


class InferenceHandler:
    def sendPhoto(self, picture):
        ret = [0., 0., 0., 0., 0., 0.]
        return ret


handler = InferenceHandler()
processor = Inference.Processor(handler)
transport = TSocket.TServerSocket("localhost", 9090)
tfactory = TTransport.TBufferedTransportFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

print("Starting thrift server in python...")
server.serve()
print("done!")
Example #23
0
    def say(self, word):
        print word


if __name__ == '__main__':
    try:
        parser = argparse.ArgumentParser(
            description='Durable File Service Participant.')
        parser.add_argument(dest='port', help='Port')
        parser.add_argument(dest='filename', help='Input File')
        args = parser.parse_args()

        port = args.port
        coorFile = args.filename

        handler = TestCoordinatorHandler()
        processor = TestCoordinator.Processor(handler)
        tsocket = TSocket.TServerSocket('0.0.0.0', args.port)
        transport = TTransport.TBufferedTransportFactory()
        protocol = TBinaryProtocol.TBinaryProtocolFactory()
        server = TServer.TThreadedServer(processor, tsocket, transport,
                                         protocol)

        host = socket.gethostname()
        host += '.cs.binghamton.edu' if host.startswith('remote') else ''
        print('TestCoordinator server running on ' + host + ':' + args.port)
        server.serve()

    except Thrift.TException as tx:
        print('%s' % (tx.message))
Example #24
0
def main():
    op = optparse.OptionParser(usage='%prog [options]', add_help_option=False)
    op.add_option('-p',
                  '--port',
                  action='store',
                  type='int',
                  dest='port',
                  default=1234,
                  help='The server port')
    op.add_option('-s',
                  '--servertype',
                  action='store',
                  type='string',
                  dest='servertype',
                  default='TGeventServer',
                  help='Type name of server')
    op.add_option('-w',
                  '--num_workers',
                  action='store',
                  type='int',
                  dest='workers',
                  default=4,
                  help='Number of worker processes')
    op.add_option('-Q',
                  '--max_queue_size',
                  action='store',
                  type='int',
                  dest='max_queue_size',
                  default=0,
                  help='Max queue size, passed to TNonblockingServer')
    op.add_option('-h',
                  '--header',
                  action='store_true',
                  help='Use the generated ContextIface')
    op.add_option('-?',
                  '--help',
                  action='help',
                  help='Show this help message and exit')

    (options, args) = op.parse_args()
    if args:
        op.error('trailing arguments: ' + ' '.join(args))

    handler = LoadHandler()
    if options.servertype == 'TGeventServer':
        # only import TGeventServer when necessary. TGeventServer calls
        # monkey_patch, which breaks other servers
        from apache.thrift.test.sync_load_handler import GeventLoadHandler
        from thrift.server import TGeventServer
        handler = GeventLoadHandler()
    processor = LoadTest.Processor(handler)

    if options.header:
        pfactory = THeaderProtocolFactory(True, \
                                          [THeaderTransport.HEADERS_CLIENT_TYPE,
                                           THeaderTransport.FRAMED_DEPRECATED,
                                           THeaderTransport.UNFRAMED_DEPRECATED,
                                           THeaderTransport.HTTP_CLIENT_TYPE])
        if options.servertype == 'TNonblockingServer':
            print 'Header transport, backwards compatible with framed'
        else:
            print 'Header transport, backwards compatible with ' + \
                'unframed, framed, http'
    else:
        if options.servertype == 'TNonblockingServer':
            print 'Framed transport'
        else:
            print 'Unframed transport'
        pfactory = TBinaryProtocolAcceleratedFactory()

    transport = TSocket.TServerSocket(options.port)
    tfactory = TTransport.TBufferedTransportFactory()
    if options.servertype == "TNonblockingServer":
        server = TNonblockingServer.TNonblockingServer(
            processor,
            transport,
            pfactory,
            maxQueueSize=options.max_queue_size)
    elif options.servertype == "TProcessPoolServer":
        server = TProcessPoolServer.TProcessPoolServer(processor, transport,
                                                       tfactory, pfactory)
        print 'Worker processes: ' + str(options.workers)
        server.setNumWorkers(options.workers)
    elif options.servertype == "TGeventServer":
        print 'Worker processes: ' + str(options.workers)
        # Gevent makes its own server transport.
        server = TGeventServer.TGeventServer(options.port, processor, None,
                                             tfactory, pfactory)
        server.setNumWorkers(options.workers)
    elif options.servertype == "TCppServer":
        server = TCppServer.TCppServer(processor)
        server.setPort(options.port)
    else:
        ServerClass = getattr(TServer, options.servertype)
        server = ServerClass(processor, transport, tfactory, pfactory)

    print 'Serving ' + options.servertype + \
        ' requests on port %d...' % (options.port,)
    server.serve()
Example #25
0
        log.value = '%d' % (val)
        self.log[logid] = log

        return val

    def getStruct(self, key):
        print 'getStruct(%d)' % (key)
        return self.log[key]

    def zip(self):
        print 'zip()'


handler = CalculatorHandler()
processor = Calculator.Processor(handler)
transport = TSocket.TServerSocket(port=9090)
tfactory = TBinaryProtocol.TBinaryProtocolFactory()
pfactory = TBinaryProtocol.TBinaryProtocolFactory()

port = 9090

server = TNonblockingServer.TNonblockingServer(processor, transport, tfactory, pfactory)
# log to stdout
log = logging.getLogger()
log.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(threadName)s - %(message)s')

ch = logging.StreamHandler(sys.stdout)
ch.setLevel(1)

ch.setFormatter(formatter)
        for i in range(0, len(operands.complexOperand1)):
            result.append(operands.complexOperand1[i] + operands.complexOperand2[i])
        return result

    def multiply(self, operands):
        if ( len(operands.complexOperand1) != len(operands.complexOperand2) ):
            raise ttypes.InvalidOperation("Los tamaños deben de ser iguales")
        return operands.complexOperand1

    def subtract(self, operands):
        if ( len(operands.complexOperand1) != len(operands.complexOperand2) ):
            raise ttypes.InvalidOperation("Los tamaños deben de ser iguales")
        result = []
        for i in range(0, len(operands.complexOperand1)):
            result.append(operands.complexOperand1[i] - operands.complexOperand2[i])
        return result


if __name__ == "__main__":
    handler = CalculadoraHandler()
    processor = CalculatorComplex.Processor(handler)
    transport = TSocket.TServerSocket(host="127.0.0.1", port=9090)
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

    print("iniciando servidor complejo...")
    server.serve()
    print("fin")
Example #27
0
            arr.append(
                numpy.random.choice(numpy.arange(0, 10),
                                    p=[
                                        0.05, 0.15, 0.05, 0.15, 0.05, 0.15,
                                        0.05, 0.15, 0.05, 0.15
                                    ]))
        return arr

    def calculateStats(self, numbers):
        print('calculateStats()')
        ans = StatsStruct()
        ans.mean = numpy.mean(numbers)
        ans.median = numpy.median(numbers)
        ans.variance = numpy.var(numbers)
        ans.std_dev = numpy.std(numbers)
        return ans


if __name__ == '__main__':
    handler = CalculatorHandler()
    processor = Calculator.Processor(handler)
    transport = TSocket.TServerSocket(host='127.0.0.1', port=9090)
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)

    print('Starting the server...')
    server.serve()
    print('done.')
Example #28
0
import sys
sys.path.append("gen-py")
from hello import HelloSvc

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer


class HelloHandler:
    def hello_func(self):
        print("[Server] Handling client request")
        return "Hello from the python server"


handler = HelloHandler()
proc = HelloSvc.Processor(handler)

trans_svr = TSocket.TServerSocket(port=9090)
trans_fac = TTransport.TBufferedTransportFactory()
proto_fac = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TSimpleServer(proc, trans_svr, trans_fac, proto_fac)
server.serve()
Example #29
0
        is_ipv6 = '-6' if ':' in server_ip else ''
        command = "iperf3 {} -J -t 1 -c {}".format(is_ipv6, server_ip)
        client_loop_cnt = 0
        while client_loop_cnt < client_retries:
            try:
                response = self.check_output(command)
                break
            except Exception:
                client_loop_cnt += 1
                error_msg = '{} retries to reach iperf3 server {}' \
                            .format(client_loop_cnt, server_ip)
                response = json.dumps({'error': error_msg})
                time.sleep(1)
        return response


if __name__ == '__main__':
    handler = TestServer()
    transport = TSocket.TServerSocket(DEFAULT_PORT)
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = THeaderProtocol.THeaderProtocolFactory()

    server = TServer.TSimpleServer(handler, transport, tfactory, pfactory)

    # You could do one of these for a multithreaded server
    # server = TServer.TThreadedServer(handler, transport, tfactory, pfactory)

    print('Starting the server...')
    server.serve()
    print('done.')
Example #30
0
def main():
    arglen = len(sys.argv)
    i = 1
    #默认端口号
    port = 9990
    #默认不持久化
    store = False
    #默认持久化文件
    store_file = u"bloom_filter.dat"
    #默认错误率
    error_rate = 0.001
    #默认最大元素数量
    element_num = 10000000
    try:
        while i < arglen:
            if sys.argv[i] == "-port" or sys.argv[i] == "-p":
                port = int(sys.argv[i + 1])
                if port < 1:
                    raise Exception(u"端口号格式错误")
                i += 2
            elif sys.argv[i] == "--store":
                store = True
                i += 1
            elif sys.argv[i] == "-file":
                store_file = sys.argv[i + 1]
                i += 2
            elif sys.argv[i] == "--version":
                print u"bloom filter server  v1.00."
                quit(0)
            elif sys.argv[i] == "--help":
                print u"""\
Usage: python bloomfilterserver.py [options]
布隆过滤器服务器

-port, -p           设置端口号,默认9990
--store             开启持久化功能,默认不开启
-file               持久化文件名,默认bloom_filter_store.data
-error-rate         错误率,默认为0.001
-element-num        元素最大数,默认为10,000,000
--version           查看版本号
--help              查看帮助信息

退出状态:
0   正常
-1  程序出错
-2  参数错误
                """
                quit(0)
            elif sys.argv[i] == u"-error-rate":
                temp_error_rate = float(sys.argv[i + 1])
                if 0 < error_rate < 1:
                    error_rate = temp_error_rate
                else:
                    raise Exception(u"错误率设置错误.")
                i += 2

            elif sys.argv[i] == u"-element-num":
                element_num = int(sys.argv[i + 1])
                if element_num < 10000:
                    raise Exception(u"最大元素数量设置错误。")
                i += 2
            else:
                raise Exception(u"无效的参数:%s" % sys.argv[i])
    except Exception as e:
        logger.error(u"参数错误,%s." % e.message)
        quit(-2)

    logger.info(
        u"布隆过滤器启动参数,port:%s,store:%s,store_file:%s,element_num:%s,error_rate:%s"
        % (port, store, store_file, element_num, error_rate))
    handler = BloomFilterServer(error_rate, element_num, store, store_file)
    #启动
    handler.start()
    processor = BloomFilterService.Processor(handler)
    hostname = socket.gethostbyname(socket.gethostname())

    logger.info(u"service %s running listen on %s:%d" %
                (handler.__class__.__name__, hostname, port))

    transport = TSocket.TServerSocket(hostname, port)

    tfactory = TTransport.TBufferedTransportFactory()

    #Protocol
    #Protocol用于对数据格式抽象,在rpc调用时序列化请求和响应。
    #TProtocol的实现包括:TJSONProtocol,TSimpleJSONProtocol,TBinaryProtocol,TBinaryPotocolAccelerated,TCompactProtocol。
    #上面每种类型,都有对应的Factory类,用于创建该类对象。
    #pfactory = TBinaryProtocol.TBinaryProtocolFactory()
    pfactory = TCompactProtocol.TCompactProtocolFactory()

    #server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
    server = TServer.TThreadPoolServer(processor, transport, tfactory,
                                       pfactory)
    server.setNumThreads(2048)

    logger.info(u"BloomFilter server Starting!")
    server.serve()
    logger.infou(u"BloomFilter server done!")