How to use the klein.Klein function in klein

To help you get started, we’ve selected a few klein 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 Netflix-Skunkworks / stethoscope / tests / test_factory.py View on Github external
def test_register_notification_api_endpoints(self):
    app = klein.Klein()
    auth = DummyAuthProvider()
    result_foo = [{'_source': {'event_timestamp': 0}}]
    result_bar = [{'_source': {'event_timestamp': 1}}]

    mock_hook = mock.Mock()
    mock_hook.obj.transform.side_effect = lambda x: x
    mock_hook_manager = stevedore.ExtensionManager.make_test_instance([mock_hook])
    mock_extension_manager = stevedore.ExtensionManager.make_test_instance(
        [get_mock_ext(result_foo, 'foo'), get_mock_ext(result_bar, 'bar')])

    with mock.patch('stethoscope.plugins.utils.instantiate_plugins') as \
        mock_instantiate_plugins:
      mock_instantiate_plugins.side_effect = [mock_extension_manager, mock_hook_manager]
      stethoscope.api.endpoints.notifications.register_notification_api_endpoints(app, config, auth)

    # see klein's test_app.py
github Netflix-Skunkworks / stethoscope / tests / test_factory.py View on Github external
def test_register_device_api_endpoints(self):
    app = klein.Klein()
    auth = DummyAuthProvider()
    result = ['foobar']

    with mock.patch('stethoscope.plugins.utils.instantiate_plugins') as \
        mock_instantiate_plugins:
      mock_instantiate_plugins.return_value = stevedore.ExtensionManager.make_test_instance(
          [get_mock_ext(result)])
      stethoscope.api.endpoints.devices.register_device_api_endpoints(app, config, auth)

    # see klein's test_app.py
    self.assertEqual(
        app.url_map.bind('devices-foo-email').match("/devices/foo/email/user@example.com"),
        ('devices-foo-email', {'email': "user@example.com"})
    )
    self.assertEqual(
        app.url_map.bind('devices-foo-macaddr').match("/devices/foo/macaddr/de:ca:fb:ad:00:00"),
github Netflix-Skunkworks / stethoscope / tests / test_validation.py View on Github external
def setUp(self):
    self.app = app = klein.Klein()
    self.auth = auth = DummyAuthProvider()
    self.config = config = {
      'DEBUG': True,
      'TESTING': True,
    }

    stethoscope.api.factory.register_error_handlers(app, config, auth)
github DBrianKimmel / PyHouse / Project / src / Modules / Computer / Web / web_server.py View on Github external
def __init__(self, p_pyhouse_obj):
        self.m_pyhouse_obj = p_pyhouse_obj
        self.State = web_utils.WS_IDLE
        self.m_web_running = False
        p_pyhouse_obj._Twisted.Application = Klein()
        LOG.info('Initialized.')
github modera / mcloud / mcloud / web.py View on Github external
import os
from klein import Klein
from twisted.web.static import File
from pkg_resources import resource_filename

app = Klein()
static_dir = resource_filename(__name__, 'static/')

@app.route('/', branch=True)
def static(request):
    return File(static_dir)

mcloud_web = app.resource
github GaoQ1 / rasa_nlu_gq / rasa_nlu_gao / server.py View on Github external
return request_params.get(name, default)


def dump_to_data_file(data):
    if isinstance(data, six.string_types):
        data_string = data
    else:
        data_string = utils.json_to_string(data)

    return utils.create_temporary_file(data_string, "_training_data")


class RasaNLU(object):
    """Class representing Rasa NLU http server"""

    app = Klein()

    def __init__(self,
                 data_router,
                 loglevel='INFO',
                 logfile=None,
                 num_threads=1,
                 token=None,
                 cors_origins=None,
                 testing=False,
                 default_config_path=None):

        self._configure_logging(loglevel, logfile)

        self.default_model_config = self._load_default_config(
                default_config_path)
github praekeltfoundation / junebug / junebug / api.py View on Github external
from junebug.utils import json_body, response
from junebug.validate import body_schema, validate

logging = logging.getLogger(__name__)


class ApiUsageError(JunebugError):
    '''Exception that is raised whenever the API is used incorrectly.
    Used for incorrect requests and invalid data.'''
    name = 'ApiUsageError'
    description = 'api usage error'
    code = http.BAD_REQUEST


class JunebugApi(object):
    app = Klein()

    def __init__(self, service, redis_config, amqp_config):
        self.service = service
        self.redis_config = redis_config
        self.amqp_config = amqp_config

    @inlineCallbacks
    def setup(self):
        self.redis = yield TxRedisManager.from_config(self.redis_config)

    @inlineCallbacks
    def teardown(self):
        yield self.redis.close_manager()

    @app.handle_errors(JunebugError)
    def generic_junebug_error(self, request, failure):
github CityOfZion / neo-python / neo / api / REST / NotificationRestApi.py View on Github external
The REST API is using the Python package 'klein', which makes it possible to
create HTTP routes and handlers with Twisted in a similar style to Flask:
https://github.com/twisted/klein

"""
import json
from klein import Klein
from neo.Implementations.Notifications.LevelDB.NotificationDB import NotificationDB
from logzero import logger
from neo.Core.Blockchain import Blockchain


class NotificationRestApi(object):
    app = Klein()

    notif = None

    def __init__(self):

        self.notif = NotificationDB.instance()

    #
    # REST API Routes
    #
    @app.route('/')
    def home(self, request):

        return """
                    <style>body {padding:20px;max-width:800px;pre { background-color:#eee; }</style>
github linux-genz / F.E.E. / ivshmsg_twisted / twisted_restapi.py View on Github external
from collections import defaultdict, OrderedDict
from pdb import set_trace
from pprint import pformat, pprint

from klein import Klein                             # Uses default reactor...

from twisted.internet import reactor as TIreactor   # ...like twisted_server
from twisted.web import server as TWserver


class MailBoxReSTAPI(object):

    N = attr.make_class('Nodes', [])
    L = attr.make_class('Links', [])

    app = Klein()   # Now its decorators can be used on methods below
    isLeaf = True   # TWserver seems to need this

    mb = None
    mm = None
    nClients = None
    nEvents = None
    server_id = None
    nodes = None

    @classmethod
    def mb2dict(cls):
        thedict = OrderedDict((
            ('nClients', cls.nClients),
            ('server_ivshmsg_id', cls.server_ivshmsg_id),
        ))
github eternaltrusts / eternal-smart / wallet / Interface / rpc_interface.py View on Github external
    @staticmethod
    def methodNotFound(message=None):
        return RpcError(-32601, message or "Method not found")

    @staticmethod
    def invalidRequest(message=None):
        return RpcError(-32600, message or "Invalid Request")

    @staticmethod
    def internalError(message=None):
        return RpcError(-32603, message or "Internal error")


class RpcInteraceApi(object):
    app = Klein()
    port = None

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

    #
    # JSON-RPC API Route
    #
    @app.route('/')
    @json_response
    @cors_header
    def home(self, request):
        body = None
        request_id = None

        try: