How to use the tinyrpc.transports.ServerTransport function in tinyrpc

To help you get started, we’ve selected a few tinyrpc examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mbr / tinyrpc / tests / test_transport.py View on Github external
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pytest

import zmq
import zmq.green

from tinyrpc.transports import ServerTransport, ClientTransport
from tinyrpc.transports.zmq import ZmqServerTransport, ZmqClientTransport


class DummyServerTransport(ServerTransport):
    def __init__(self):
        self.messages = []
        self.clients = {}

    def receive_message(self):
        return self.messages.pop()

    def send_reply(self, context, message):
        if not isinstance(message, str):
            raise TypeError('Message must be str().')
        self.clients[context].messages.append(message)


class DummyClientTransport(ClientTransport):
    def __init__(self, server):
        self.server = server
github osrg / ryu / ryu / app / wsgi.py View on Github external
if hasattr(self, '__before__'):
            self.__before__()

        kwargs = self.req.urlvars.copy()
        for attr in self.special_vars:
            if attr in kwargs:
                del kwargs[attr]

        return getattr(self, action)(req, **kwargs)


class WebSocketDisconnectedError(Exception):
    pass


class WebSocketServerTransport(ServerTransport):
    def __init__(self, ws):
        self.ws = ws

    def receive_message(self):
        message = self.ws.wait()
        if message is None:
            raise WebSocketDisconnectedError()
        context = None
        return context, message

    def send_reply(self, context, reply):
        self.ws.send(six.text_type(reply))


class WebSocketRPCServer(RPCServer):
    def __init__(self, ws, rpc_callback):
github MatrixAINetwork / go-matrix / cmd / clef / pythonsigner.py View on Github external
can access process memory."""

try:
    import urllib.parse as urlparse
except ImportError:
    import urllib as urlparse

class StdIOTransport(ServerTransport):
    """ Uses std input/output for RPC """
    def receive_message(self):
        return None, urlparse.unquote(sys.stdin.readline())

    def send_reply(self, context, reply):
        print(reply)

class PipeTransport(ServerTransport):
    """ Uses std a pipe for RPC """

    def __init__(self,input, output):
        self.input = input
        self.output = output

    def receive_message(self):
        data = self.input.readline()
        print(">> {}".format( data))
        return None, urlparse.unquote(data)

    def send_reply(self, context, reply):
        print("<< {}".format( reply))
        self.output.write(reply)
        self.output.write("\n")
github MatrixAINetwork / go-matrix / run / clef / pythonsigner.py View on Github external
from tinyrpc.dispatch import public,RPCDispatcher
from tinyrpc.server import RPCServer

""" This is a POC example of how to write a custom UI for Clef. The UI starts the
clef process with the '--stdio-ui' option, and communicates with clef using standard input / output.

The standard input/output is a relatively secure way to communicate, as it does not require opening any ports
or IPC files. Needless to say, it does not protect against memory inspection mechanisms where an attacker
can access process memory."""

try:
    import urllib.parse as urlparse
except ImportError:
    import urllib as urlparse

class StdIOTransport(ServerTransport):
    """ Uses std input/output for RPC """
    def receive_message(self):
        return None, urlparse.unquote(sys.stdin.readline())

    def send_reply(self, context, reply):
        print(reply)

class PipeTransport(ServerTransport):
    """ Uses std a pipe for RPC """

    def __init__(self,input, output):
        self.input = input
        self.output = output

    def receive_message(self):
        data = self.input.readline()
github MatrixAINetwork / go-matrix / cmd / clef / pythonsigner.py View on Github external
from tinyrpc.dispatch import public,RPCDispatcher
from tinyrpc.server import RPCServer

""" This is a POC example of how to write a custom UI for Clef. The UI starts the
clef process with the '--stdio-ui' option, and communicates with clef using standard input / output.

The standard input/output is a relatively secure way to communicate, as it does not require opening any ports
or IPC files. Needless to say, it does not protect against memory inspection mechanisms where an attacker
can access process memory."""

try:
    import urllib.parse as urlparse
except ImportError:
    import urllib as urlparse

class StdIOTransport(ServerTransport):
    """ Uses std input/output for RPC """
    def receive_message(self):
        return None, urlparse.unquote(sys.stdin.readline())

    def send_reply(self, context, reply):
        print(reply)

class PipeTransport(ServerTransport):
    """ Uses std a pipe for RPC """

    def __init__(self,input, output):
        self.input = input
        self.output = output

    def receive_message(self):
        data = self.input.readline()
github mbr / tinyrpc / tinyrpc / transports / websocket.py View on Github external
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import Queue

from . import ServerTransport
from geventwebsocket.resource import WebSocketApplication, Resource


class WSServerTransport(ServerTransport):
    '''
    Requires :py:mod:`geventwebsocket`.

    Due to the nature of WS, this transport has a few pecularities: It must
    be run in a thread, greenlet or some other form of concurrent execution
    primitive.
    
    This is due to
    :py:prop:`~tinyrpc.transports.websocket.WSServerTransport.handle` which is
    a :py:class:`geventwebsocket.resource.Resource` that joins a wsgi handler 
    for the / and a WebSocket handler for the /ws path. These resource is
    used in combination with a :py:class:`geventwebsocket.server.WebSocketServer`
    that blocks while waiting for a call to
    :py:func:`~tinyrpc.transports.wsgi.WSServerTransport.send_reply`.

    The parameter ``queue_class`` must be used to supply a proper queue class
github mbr / tinyrpc / tinyrpc / transports / zmq.py View on Github external
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import  # needed for zmq import
import zmq

from . import ServerTransport, ClientTransport


class ZmqServerTransport(ServerTransport):
    """Server transport based on a :py:const:`zmq.ROUTER` socket.

    :param socket: A :py:const:`zmq.ROUTER` socket instance, bound to an
                   endpoint.
    """

    def __init__(self, socket):
        self.socket = socket

    def receive_message(self):
        msg = self.socket.recv_multipart()
        return msg[:-1], msg[-1]

    def send_reply(self, context, reply):
        self.socket.send_multipart(context + [reply])
github mbr / tinyrpc / tinyrpc / transports / wsgi.py View on Github external
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import queue as Queue
from typing import Tuple, Any

from werkzeug.wrappers import Response, Request

from . import ServerTransport


class WsgiServerTransport(ServerTransport):
    """WSGI transport.

    Requires :py:mod:`werkzeug`.

    Due to the nature of WSGI, this transport has a few peculiarities: It must
    be run in a thread, greenlet or some other form of concurrent execution
    primitive.

    This is due to
    :py:func:`~tinyrpc.transports.wsgi.WsgiServerTransport.handle` blocking
    while waiting for a call to
    :py:func:`~tinyrpc.transports.wsgi.WsgiServerTransport.send_reply`.

    The parameter ``queue_class`` must be used to supply a proper queue class
    for the chosen concurrency mechanism (i.e. when using :py:mod:`gevent`,
    set it to :py:class:`gevent.queue.Queue`).
github MatrixAINetwork / go-matrix / run / clef / pythonsigner.py View on Github external
can access process memory."""

try:
    import urllib.parse as urlparse
except ImportError:
    import urllib as urlparse

class StdIOTransport(ServerTransport):
    """ Uses std input/output for RPC """
    def receive_message(self):
        return None, urlparse.unquote(sys.stdin.readline())

    def send_reply(self, context, reply):
        print(reply)

class PipeTransport(ServerTransport):
    """ Uses std a pipe for RPC """

    def __init__(self,input, output):
        self.input = input
        self.output = output

    def receive_message(self):
        data = self.input.readline()
        print(">> {}".format( data))
        return None, urlparse.unquote(data)

    def send_reply(self, context, reply):
        print("<< {}".format( reply))
        self.output.write(reply)
        self.output.write("\n")
github mbr / tinyrpc / tinyrpc / transports / callback.py View on Github external
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from typing import Callable, Tuple, Any

from . import ServerTransport


class CallbackServerTransport(ServerTransport):
    """Callback server transport.

    The :py:class:`CallbackServerTransport` uses the provided callbacks to implement
    communication with the counterpart.

    Used when tinyrpc is part of a system where it cannot directly attach
    to a socket or stream. The methods :py:meth:`receive_message` and
    :py:meth:`send_reply` are implemented by callback functions that are
    set when constructed.

    :param callable reader: Called when the transport wants to receive a new request.

        :returns: The RPC request.
        :rtype: bytes

    :param callable writer(reply): Called to return the response to the client.