Exemple #1
0
site_rank = {1 : ("Facebook", 750000000),
             2 : ("Twitter",  250000000),
             3 : ("LinkedIn", 110000000) }

class SocialLookupHandler(SocialLookup.Iface):
    def GetSiteByRank(self, rank):
        tup = site_rank[rank]
        return "" if (None==tup) else tup[0]

    def GetSiteRankByName(self, name, allowPartialMatch):
        for rank, value in site_rank.items():
            if allowPartialMatch:
                if value[0][:len(name)] == name:
                    return rank
            else:
                if value[0] == name:
                    return rank
        return 0

    def GetSitesByUsers(self, minUserCount, maxUserCount):
        return [v[0] for k, v in site_rank.items() 
                if v[1] >= minUserCount and v[1] <= maxUserCount]

if __name__ == "__main__": 
    svr_trans = TSocket.TServerSocket(port=8585)
    processor = SocialLookup.Processor(SocialLookupHandler())
    server = TServer.TSimpleServer(processor, svr_trans)
    server.serve()

Exemple #2
0
import sys
import glob
sys.path.append("python_scripts/gen-py")

from thrift.transport import TSocket
from thrift.server import TServer
import thrift_solr
from thrift_solr import SolrService

import mc_solr
import solr_facets_wrapper


class SolrHandler:
    def media_counts(self, q, facet_field, fq, mincount):
        solr = mc_solr.py_solr_connection()

        return solr_facets_wrapper.facet_query_counts(solr, q, facet_field, fq,
                                                      mincount)


handler = SolrHandler()
processor = SolrService.Processor(handler)
listening_socket = TSocket.TServerSocket(port=9090)
server = TServer.TThreadPoolServer(processor, listening_socket)

print("[Server] Started")
server.serve()
Exemple #3
0
                print('[' + SERVER_PORT[0] + ':' + str(SERVER_PORT[1]) +
                      '] Insufficient funds!')
                return False
            else:
                bal_fromAccount = float(bal_fromAccount)
                bal_toAccount = float(bal_toAccount)
                assert float(
                    self.AccountInformationClient.updateBalance(
                        fromAccount,
                        str(-1 * amount))) == bal_fromAccount - amount
                assert float(
                    self.AccountInformationClient.updateBalance(
                        toAccount, str(amount))) == bal_toAccount + amount
                return True


if __name__ == '__main__':
    handler = MoneyTransferHandler()
    processor = MoneyTransfer.Processor(handler)
    transport = TSocket.TServerSocket(host=SERVER_PORT[0], port=SERVER_PORT[1])
    tfactory = TTransport.TFramedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

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

    print('[' + SERVER_PORT[0] + ':' + str(SERVER_PORT[1]) + ']' +
          ' Starting the MoneyTransferServer...')
    server.serve()
    print('[' + SERVER_PORT[0] + ':' + str(SERVER_PORT[1]) + ']' +
          ' MoneyTransferServer done.')
Exemple #4
0
# -*- coding:utf-8 -*-
__author__ = "作者"

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(port=8899)
    transportFactory = TTransport.TFramedTransportFactory()
    protocolFactory = TCompactProtocol.TCompactProtocolFactory()

    server = TServer.TSimpleServer(processor, serverSocket, transportFactory,
                                   protocolFactory)
    server.serve()

except Thrift.TException, ex:
    print '%s' % ex.message
Exemple #5
0
        result = Result()
        result.result = num1 + num2
        return result

    def Subtract(self, num1, num2):
        result = Result()
        result.result = num1 - num2
        return result

    def Multiply(self, num1, num2):
        result = Result()
        result.result = num1 * num2
        return result

    def Divide(self, num1, num2):
        result = Result()
        if num2 == 0:
            result.message = "Impossible to divide by zero."
        else:
            result.result = num1 / num2
        return result


if __name__ == "__main__":
    serverTransport = TSocket.TServerSocket(port=5000)
    processor = CalculatorService.Processor(CalculatorServiceHandler())
    server = TServer.TSimpleServer(processor, serverTransport)
    print(">> Starting service...")
    server.serve()
    print(">> Calculator Service Thrift started.")
# coding=utf-8

from py.thrift.generated import PersonService
from PersonServiceImpl import PersonServiceImpl

from thrift import Thrift

from thrift.server import TNonblockingServer
from thrift.server import TServer
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TCompactProtocol

try:
    personServerHandler = PersonServiceImpl()
    processer = PersonService.Processor(personServerHandler)
    socket = TSocket.TServerSocket(host='127.0.0.1', port=8899)
    transportFactory = TTransport.TFramedTransportFactory()
    protocalFactory = TCompactProtocol.TCompactProtocolFactory()

    server = TServer.TSimpleServer(processer, socket, transportFactory,
                                   protocalFactory)
    server.serve()

except Thrift.TException as tx:
    print('----')
Exemple #7
0
def create_server():
    handler = ShortTermMemoryThriftServer()
    return TServer.TSimpleServer(ShortMemoryService.Processor(handler),
                                 TSocket.TServerSocket(port=port),
                                 TTransport.TBufferedTransportFactory(),
                                 TBinaryProtocol.TBinaryProtocolFactory())
Exemple #8
0
def run():
    parser = argparse.ArgumentParser(description=__doc__, prog='lesedi')
    parser.add_argument('--version',
                        action='version',
                        version='%(prog)s {}'.format(__version__))
    parser.add_argument('--log-file', help='the log file to write to')
    parser.add_argument('--log-level',
                        default='INFO',
                        type=str.upper,
                        choices=['DEBUG', 'INFO', 'WARN', 'ERROR', 'CRITICAL'],
                        help='the level of logging to use.')

    parser.add_argument('--config', help='path to the configuration file')

    parser.add_argument('--host',
                        default=constants.DEFAULT_HOST,
                        help='the TCP interface to listen on')
    parser.add_argument('--port',
                        default=constants.DEFAULT_PORT,
                        type=int,
                        help='the TCP port to listen on')

    arguments = parser.parse_args()

    if not arguments.log_file:
        logging.basicConfig(stream=sys.stdout, level=arguments.log_level)
    else:
        logging.basicConfig(filename=arguments.log_file,
                            format='%(asctime)s [%(levelname)5s]: %(message)s',
                            level=arguments.log_level)
    logger = logging.getLogger(__name__)

    if arguments.config:
        try:
            config = configparser.ConfigParser()

            with open(arguments.config, 'r') as f:
                config.readfp(f)
        except IOError as e:
            sys.exit('Error while reading config file "{}"'.format(
                arguments.config))
    else:
        # If no config is given, assume that all services are running locally.
        config = {
            'aux': {
                'host': '127.0.0.1'
            },
            'dome': {
                'host': '127.0.0.1'
            },
            'focuser': {
                'host': '127.0.0.1'
            },
            'rotator': {
                'host': '127.0.0.1'
            },
            'telescope': {
                'host': '127.0.0.1'
            },
        }

    handler = Handler(config)

    processor = Service.Processor(handler)
    transport = TSocket.TServerSocket(host=arguments.host, port=arguments.port)
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

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

    logger.info('Listening on {}:{}'.format(arguments.host, arguments.port))

    try:
        server.serve()
    except (KeyboardInterrupt, SystemExit):
        sys.exit(0)
    finally:
        transport.close()
Exemple #9
0
class HelloWorldHandler():
    def __init__(self):
        pass

    def ping(self):
        return 'pong!'

    def say(self, message):
        ret = "server received: " + message
        print(ret)
        return ret


if __name__ == '__main__':
    handler = HelloWorldHandler()  #build your own handler
    processor = HelloWorld.Processor(
        handler)  ##get a processor from a handler that you built
    transport = TSocket.TServerSocket('localhost',
                                      9090)  #get a server transport
    tfactory = TTransport.TBufferedTransportFactory(
    )  ##get a transport factory
    pfactory = TBinaryProtocol.TBinaryProtocolFactory(
    )  ##get a protocol factory

    server = TServer.TSimpleServer(processor, transport, tfactory,
                                   pfactory)  #get a server from the settings

    print("begin the server on localhost,9090")
    server.serve()
    print("Suspend the service on localhost,9090")
Exemple #10
0
sys.path.append("gen-py")
from thrift.transport import TTransport
from thrift.transport import TSocket
from thrift.protocol import TJSONProtocol
from thrift.server import TServer
from simple import Message


class MessageHandler(Message.Iface):
    msgs = ["Apache Thrift!!", "Childhood is a short season", "'Twas brillig"]

    def __init__(self):
        self.msg_index = 0

    def motd(self):
        self.msg_index += 1
        print("Call count: %s" % self.msg_index)
        return MessageHandler.msgs[self.msg_index % 3]


if __name__ == "__main__":
    handler = MessageHandler()
    proc = Message.Processor(handler)
    svr_trans = TSocket.TServerSocket(port=8585)

    trans_fac = TTransport.TFramedTransportFactory()
    proto_fac = TJSONProtocol.TJSONProtocolFactory()

    server = TServer.TThreadedServer(proc, svr_trans, trans_fac, proto_fac)
    server.serve()
def start_extension(name="<unknown>",
                    version="0.0.0",
                    sdk_version="1.8.0",
                    min_sdk_version="1.8.0"):
    """Start your extension by communicating with osquery core and starting
    a thrift server.

    Keyword arguments:
    name -- the name of your extension
    version -- the version of your extension
    sdk_version -- the version of the osquery SDK used to build this extension
    min_sdk_version -- the minimum version of the osquery SDK that you can use
    """
    args = parse_cli_params()

    # Disable logging for the thrift module (can be loud).
    logging.getLogger('thrift').addHandler(logging.NullHandler())

    client = ExtensionClient(path=args.socket)

    if not client.open(args.timeout):
        if args.verbose:
            message = "Could not open socket %s" % args.socket
            raise ExtensionException(
                code=1,
                message=message,
            )
        return
    ext_manager = ExtensionManager()

    # try connecting to the desired osquery core extension manager socket
    try:
        status = client.extension_manager_client().registerExtension(
            info=InternalExtensionInfo(
                name=name,
                version=version,
                sdk_version=sdk_version,
                min_sdk_version=min_sdk_version,
            ),
            registry=ext_manager.registry(),
        )
    except socket.error:
        message = "Could not connect to %s" % args.socket
        raise ExtensionException(
            code=1,
            message=message,
        )

    if status.code != 0:
        raise ExtensionException(
            code=1,
            message=status.message,
        )

    # Start a watchdog thread to monitor the osquery process.
    rt = threading.Thread(target=start_watcher, args=(client, args.interval))
    rt.daemon = True
    rt.start()

    # start a thrift server listening at the path dictated by the uuid returned
    # by the osquery core extension manager
    ext_manager.uuid = status.uuid
    processor = Processor(ext_manager)

    transport = None
    if sys.platform == 'win32':
        transport = TPipeServer(
            pipe_name="{}.{}".format(args.socket, status.uuid))
    else:
        transport = TSocket.TServerSocket(unix_socket=args.socket + "." +
                                          str(status.uuid))

    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()
    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
    server.serve()
    return _requires_authorization


class HelloWorldHandler(object):
    def ping(self):
        print "ping ..."

    @requires_authorization('Basic Authenticate required')
    def echo(self, msg):
        return 'Hello %s: %s' % (g.user, msg)


handler = HelloWorldHandler()
processor = HelloWorld.Processor(handler)
pfactory = TBinaryProtocol.TBinaryProtocolFactory()
hello_server = TServer.TServer(processor, None, None, None, pfactory, pfactory)

app = Flask(__name__)


@app.route('/_thrift', methods=['POST'])
def _thrift():
    itrans = TTransport.TMemoryBuffer(request.data)
    otrans = TTransport.TMemoryBuffer()
    iprot = hello_server.inputProtocolFactory.getProtocol(itrans)
    oprot = hello_server.outputProtocolFactory.getProtocol(otrans)
    hello_server.processor.process(iprot, oprot)
    return make_response(otrans.getvalue())


if __name__ == '__main__':
Exemple #13
0
class EmailServiceHandler:
    def sendEmailMessage(self, email, message):
        print(email + message)
        messageObj = MIMEText(message, 'plain', 'utf-8')
        messageObj['From'] = sender
        messageObj['To'] = email
        messageObj['Subject'] = Header("邮箱验证", 'uf-8')

        try:
            smtpObj = smtplib.SMTP('smtp.163.com')
            smtpObj.login(sender, authorCode)
            smtpObj.sendmail(sender, [email], messageObj.as_string())
            print("发送成功")
            return True
        except smtplib.SMTPException:
            print("发送失败")
            return False


if __name__ == '__main__':

    serverSocket = TSocket.TServerSocket(host='127.0.0.1', port='5174')
    transportFactory = TTransport.TFramedTransportFactory()
    protocolFactory = TBinaryProtocol.TBinaryProtocolFactory()
    handler = EmailServiceHandler()
    processor = EmailService.Processor(handler)
    thriftServer = TServer.TSimpleServer(handler, serverSocket,
                                         transportFactory, protocolFactory)
    print("启动中")
    thriftServer.serve()
Exemple #14
0
    def multiplicacion(self, n1, n2):
        print("multiplicar(%d,%d)" % (n1, n2))
        return n1 * n2

    def division(self, n1, n2):
        print("dividir(%d,%d)" % (n1, n2))
        return n1 / n2


# Crear una instancia del manejador
manejador = CalculadoraHandler()

# Iniciacilizar un procesador para el servicio
procesador = CalculadoraServicio.Processor(manejador)

# Crear el socket TCP
puerto = 9090
transporte_serv = TSocket.TServerSocket(port=puerto)

# Buffer -> Eficiencia
transporte_fact = TTransport.TBufferedTransportFactory()

# Protocolo binario
protocolo_fact = TBinaryProtocol.TBinaryProtocolFactory()

# crear un servidor con funcionalidad básica
servidor = TServer.TSimpleServer(procesador, transporte_serv, transporte_fact,
                                 protocolo_fact)
print("Iniciando el servidor en el puerto %s" % puerto)
servidor.serve()
Exemple #15
0
def get_async_server(service, handler, port):
    processor = service.Processor(handler)
    transport = TSocket.TServerSocket(port=port)
    transport_factory = TTransport.TFramedTransport(transport)
    protocol_factory = TBinaryProtocol.TBinaryProtocolFactory()
    return TServer.TThreadedServer(processor, transport, transport_factory, protocol_factory)
Exemple #16
0
    def echoHello(self, param):
        result = "你发的字符串是:" + param
        return result

    def uploadFile(self, binaryData, filePath, flag):
        import os
        if flag == 0:
            if os.path.exists(filePath):
                os.remove(filePath)
        # 以追加模式+二进制模式打开
        fp = open(filePath, "ab")
        try:
            fp.write(binaryData)
        finally:
            fp.close()


handler = HelloHandler()
processor = Hello.Processor(handler)

socket = TSocket.TServerSocket(host="localhost", port=9000)
factory = TTransport.TFramedTransportFactory()
protocol = TCompactProtocol.TCompactProtocolFactory()

#不支持windows
#server = TServer.TForkingServer(processor, socket, factory, protocol)
server = TServer.TThreadPoolServer(processor, socket, factory, protocol)

print "python start server port: 9000"
server.serve()
Exemple #17
0
def main(cfg):
    if cfg.unix:
        if cfg.addr == "":
            sys.exit("invalid listener unix domain socket: {}".format(
                cfg.addr))
    else:
        try:
            (host, port) = cfg.addr.rsplit(":", 1)
            port = int(port)
        except ValueError:
            sys.exit("invalid listener address: {}".format(cfg.addr))

    if cfg.response == "success":
        handler = SuccessHandler()
    elif cfg.response == "idl-exception":
        handler = IDLExceptionHandler()
    elif cfg.response == "exception":
        # squelch traceback for the exception we throw
        logging.getLogger().setLevel(logging.CRITICAL)
        handler = ExceptionHandler()
    else:
        sys.exit("unknown server response mode {0}".format(cfg.response))

    processor = Example.Processor(handler)
    if cfg.service is not None:
        # wrap processor with multiplexor
        multi = TMultiplexedProcessor.TMultiplexedProcessor()
        multi.registerProcessor(cfg.service, processor)
        processor = multi

    if cfg.protocol == "finagle":
        # wrap processor with finagle request/response header handler
        processor = TFinagleServerProcessor.TFinagleServerProcessor(processor)

    if cfg.unix:
        transport = TSocket.TServerSocket(unix_socket=cfg.addr)
    else:
        transport = TSocket.TServerSocket(host=host, port=port)

    if cfg.transport == "framed":
        transport_factory = TTransport.TFramedTransportFactory()
    elif cfg.transport == "unframed":
        transport_factory = TTransport.TBufferedTransportFactory()
    elif cfg.transport == "header":
        if cfg.protocol == "binary":
            transport_factory = THeaderTransport.THeaderTransportFactory(
                THeaderTransport.T_BINARY_PROTOCOL)
        elif cfg.protocol == "compact":
            transport_factory = THeaderTransport.THeaderTransportFactory(
                THeaderTransport.T_COMPACT_PROTOCOL)
        else:
            sys.exit(
                "header transport cannot be used with protocol {0}".format(
                    cfg.protocol))
    else:
        sys.exit("unknown transport {0}".format(cfg.transport))

    if cfg.protocol == "binary":
        protocol_factory = TBinaryProtocol.TBinaryProtocolFactory()
    elif cfg.protocol == "compact":
        protocol_factory = TCompactProtocol.TCompactProtocolFactory()
    elif cfg.protocol == "json":
        protocol_factory = TJSONProtocol.TJSONProtocolFactory()
    elif cfg.protocol == "finagle":
        protocol_factory = TFinagleServerProtocol.TFinagleServerProtocolFactory(
        )
    else:
        sys.exit("unknown protocol {0}".format(cfg.protocol))

    print("Thrift Server listening on {0} for {1} {2} requests".format(
        cfg.addr, cfg.transport, cfg.protocol))
    if cfg.service is not None:
        print("Thrift Server service name {0}".format(cfg.service))
    if cfg.response == "idl-exception":
        print("Thrift Server will throw IDL exceptions when defined")
    elif cfg.response == "exception":
        print("Thrift Server will throw Thrift exceptions for all messages")

    server = TServer.TThreadedServer(processor, transport, transport_factory,
                                     protocol_factory)
    try:
        server.serve()
    except KeyboardInterrupt:
        print
Exemple #18
0
# Apache Thrift Hello World Python Server

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 thrift, 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)

print("[Server] Started")
server.serve()

Exemple #19
0
    def verify_game(self, game):
        if game not in self.GAMES:
            raise GameException(name + ' is not a valid game name')

    def sanitize_argument(self, argument):
        '''Removes all characters that aren't common typeable ASCII characters
        from the given program argument.
        '''
        # The only visible ASCII characters are Space through Tilde.
        return re.sub('[^ -~]', '', argument)


class GameException(Exception):
    pass


if __name__ == '__main__':
    with DaemonContext():
        port = 24444
        path = '../bin'
        handler = RequestHandler(path)
        processor = GamestateRequestHandler.Processor(handler)
        transport = TSocket.TServerSocket(port)
        transport_factory = TTransport.TBufferedTransportFactory()
        protocol_factory = TBinaryProtocol.TBinaryProtocolFactory()
        server = TServer.TThreadedServer(processor, transport,
                                         transport_factory, protocol_factory)
        print 'GamesmanClassic server listening on port %d...' % (port, )
        server.serve()
from KnowledgePolicyListener import KnowledgePolicyListener
from service import KnowledgeGraphPyService
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

_HOST = "0.0.0.0"
_PORT = 9000

if __name__ == "__main__":
    handler = KnowledgePolicyListener()
    processor = KnowledgeGraphPyService.Processor(handler)
    transport = TSocket.TServerSocket(_HOST, _PORT)
    tFactory = TTransport.TBufferedTransportFactory()
    pFactory = TBinaryProtocol.TBinaryProtocolFactory()
    rpcServer = TServer.TSimpleServer(processor, transport, tFactory, pFactory)
    rpcServer.serve()


        def wrappee(*args, **kwargs):
            logging.debug('in decorator before wrapee with flag ' +
                          str(decorator_self._thrift_class.__name__))

            dec_name = str(
                decorator_self._thrift_class.__name__).split(".")[-1]
            print(dec_name)

            assert "use_rpc" in kwargs.keys() and "server" in kwargs.keys(), \
             "Wrapped function must be subclass of RPC."

            if "use_rpc" in kwargs.keys() and "server" in kwargs.keys() \
              and kwargs["use_rpc"] and kwargs["server"]:

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

                handler = original_clazz(*args, **kwargs)
                processor = decorator_self._thrift_class.Processor(handler)
                transport = TSocket.TServerSocket(port=decorator_self._port)
                tfactory = TTransport.TBufferedTransportFactory()
                pfactory = TBinaryProtocol.TBinaryProtocolFactory()

                self.__inst = handler

                server = TServer.TThreadPoolServer(processor, transport,
                                                   tfactory, pfactory)
                server.setNumThreads(cpu_count() * 4)

                logging.info("Serving: " + dec_name)
                server.serve()
                logging.info('Done: ' + dec_name)

            elif "use_rpc" in kwargs.keys() and "server" in kwargs.keys() \
              and kwargs["use_rpc"] and not kwargs["server"]:

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

                # Make socket
                self._transport = TSocket.TSocket(host=dec_name,
                                                  port=decorator_self._port)
                # Buffering is critical. Raw sockets are very slow
                self._transport = TTransport.TBufferedTransport(
                    self._transport)
                # Connect!
                self._transport.open()
                # Wrap in a protocol
                protocol = TBinaryProtocol.TBinaryProtocol(self._transport)
                # Create a client to use the protocol encoder
                client = decorator_self._thrift_class.Client(protocol)
                logging.info("Client (" + dec_name +
                             ") connected to server: " +
                             str(self._transport.isOpen()))

                return client

            else:
                return original_clazz(*args, **kwargs)
def create_server():
    handler = MusicPiThriftHandler()
    return TServer.TSimpleServer(GenericPiThriftService.Processor(handler),
                                 TSocket.TServerSocket(port=port),
                                 TTransport.TBufferedTransportFactory(),
                                 TBinaryProtocol.TBinaryProtocolFactory())
Exemple #23
0
from idls.is_idl.image_searcher.ttypes import *

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

# my custom utility
from util.util import *
from is_handler import ImageSearcherServiceHandler

ishandler = ImageSearcherServiceHandler(is_conf, islogger)
isprocessor = ImageSearcherService.Processor(ishandler)
is_ip = is_conf["services"]["is"]["ip"]
is_port = is_conf["services"]["is"]["port"]
istransport = TSocket.TServerSocket(is_ip, is_port)
istfactory = TTransport.TBufferedTransportFactory()
ispfactory = TCompactProtocol.TCompactProtocolFactory()

is_server = TServer.TSimpleServer(isprocessor, istransport, istfactory,
                                  ispfactory)

islogger.info(
    "=================================================================")
islogger.info("Starting Search Plan in ip \"{}\" and port {}".format(
    is_ip, is_port))

is_server.serve()

islogger.info("Done")
Exemple #24
0
            self.check_output(command)
        except Exception as e:
            # Ignoring "File exists" error
            if "exit status 2" not in str(e):
                raise FbossBaseError("Error adding address: {}".format(str(e)))
        return True

    def _cleanUpAddedInterfaces(self):
        for ifName in self.added_interfaces:
            command = "ip link del dev {}".format(ifName)
            try:
                self.check_output(command)
            except Exception as e:
                self.log.info("Error deleting interface: {}".format(str(e)))


if __name__ == '__main__':
    with TestServer() as handler:
        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.')
import sys
sys.path.append("gen-py")
from thrift.transport import TTransport
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer

from levels import CanLevels
from levels import ttypes

wcans = {}


class CanLevelsHandler:
    def get_cans_above_threshold(self, percent_full):
        return ttypes.can_levels(count=2, can_levels=wcans)

    def update_can_level(self, can_id, percent_full):
        wcans[can_id] = percent_full


handler = CanLevelsHandler()
proc = CanLevels.Processor(handler)
trans_ep = TSocket.TServerSocket(port=9095)
trans_fac = TTransport.TBufferedTransportFactory()
proto_fac = TBinaryProtocol.TBinaryProtocolFactory()
server = TServer.TThreadedServer(proc, trans_ep, trans_fac, proto_fac)

print("[Server] Started")
server.serve()
Exemple #26
0
        batch = Batch()
        units = []
        for j in range(row_num):
            units.append(Unit(**single_batch.iloc[j].to_dict()))
        batch.units = units
        batch.batch_id = batch_id + i
        batches.append(batch)
        start_index += batch_unit
    resp.batches = batches
    return resp, batch.batch_id


handler = ParseRequestHandler()
processor = ParseRequest.Processor(handler)
protocol = TJSONProtocol.TJSONProtocolFactory()
server = TServer.TServer(processor, None, None, None, protocol, protocol)


@app.route('/api/v2/batches', methods=['POST'])
def get_binary_samples():
    itrans = TTransport.TMemoryBuffer(request.data)
    otrans = TTransport.TMemoryBuffer()
    iprot = server.inputProtocolFactory.getProtocol(itrans)
    oprot = server.outputProtocolFactory.getProtocol(otrans)
    server.processor.process(iprot, oprot)
    return otrans.getvalue()


if __name__ == '__main__':
    app.run(debug=True)
Exemple #27
0
from thrift.server import TServer
from thrift.TMultiplexedProcessor import TMultiplexedProcessor

from Config import Config

from DemoHandler import DemoHandler

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)-15s %(message)s',
                        datefmt='%Y-%m-%dT%H:%M:%S')
    logging.Formatter.converter = time.gmtime

    processor = TMultiplexedProcessor()

    processor.registerProcessor("Demo", DemoService.Processor(DemoHandler()))

    transport = TSocket.TServerSocket('10.1.20.59', 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)
    server = TServer.TForkingServer(processor, transport, tfactory, pfactory)

    logging.info('Starting the server...')
    server.serve()
    logging.info('done.')
Exemple #28
0
def get_server(service, handler, port):
    processor = service.Processor(handler)
    transport = TSocket.TServerSocket(port=port)
    transport_factory = TTransport.TBufferedTransportFactory()
    protocol_factory = TBinaryProtocol.TBinaryProtocolFactory()
    return TServer.TSimpleServer(processor, transport, transport_factory, protocol_factory)
        return True

    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("Task Email", "utf-8")
        try:
            # smtpObj = smtplib.SMTP('smtp.google.com')
            smtpObj = smtplib.SMTP('smtp.gmail.com', 587)
            smtpObj.login(sender, authCode)
            smtpObj.sendmail(sender, [email], messageObj.as_string())
            return True
        except smtplib.SMTPException, ex:
            print "send email failed"
            print ex
            return False


if __name__ == '__main__':
    handler = MessageServiceHandler()
    processor = MessageService.Processor(handler)
    transport = TSocket.TServerSocket("localhost", "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"
Exemple #30
0
    def kill(self):
        os._exit(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')
        args = parser.parse_args()

        handler = TestFileStoreHandler()
        processor = TestFileStore.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('TestFileStore server running on ' + host + ':' + args.port)
        server.serve()

    except Thrift.TException as tx:
        print('%s' % (tx.message))