Beispiel #1
0
def loadresolvers(paths):
    """Load input path modules in order to register external resolvers.

    :param list paths: list of paths to load."""

    for path in paths:
        lookup(path)
Beispiel #2
0
    def processexpr(self, expr, ctx=None, **kwargs):

        result = []

        if ctx is None:
            ctx = Context()

        items = kwargs.setdefault('items', self.items)

        for item in items:
            try:
                getsubitem(item, expr.name, error=True)

            except KeyError:
                pass

            else:
                result.append(item)

        if not result:  # if not item match, try to lookup the expression
            try:
                result = lookup(expr.name)

            except ImportError:
                if isinstance(items, list):
                    items[:] = result

        else:
            if isinstance(items, list):
                items[:] = result

        ctx[expr] = result

        return result
Beispiel #3
0
    def __call__(self, svalue):

        result = []

        if svalue:

            for item in svalue.split(','):

                item = item.strip()

                if not isinstance(item, self.ptype):

                    try:
                        item = self.ptype(item)

                    except (TypeError, ValueError):

                        item = lookup(item)

                        if issubclass(item, self.ptype):

                            item = item()

                if isinstance(item, self.ptype):

                    result.append(item)

                else:
                    raise TypeError(
                        'Wrong item type, {0} expected'.format(self.ptype)
                    )

        return result
Beispiel #4
0
    def read_callback(self, value):
        if value is None:
            value = read_callback

        if isinstance(value, string_types):
            value = lookup(value)

        self._read_callback = value
Beispiel #5
0
    def shutdown_callback(self, value):
        if value is None:
            value = shutdown_callback

        if isinstance(value, string_types):
            value = lookup(value)

        self._shutdown_callback = value
Beispiel #6
0
    def write_callback(self, value):
        if value is None:
            value = write_callback

        if isinstance(value, string_types):
            value = lookup(value)

        self._write_callback = value
Beispiel #7
0
    def notification_callback(self, value):
        if value is None:
            value = notification_callback

        if isinstance(value, string_types):
            value = lookup(value)

        self._notification_callback = value
Beispiel #8
0
    def read_callback(self, value):
        if value is None:
            value = read_callback

        if isinstance(value, string_types):
            value = lookup(value)

        self._read_callback = value
Beispiel #9
0
    def shutdown_callback(self, value):
        if value is None:
            value = shutdown_callback

        if isinstance(value, string_types):
            value = lookup(value)

        self._shutdown_callback = value
Beispiel #10
0
    def exception_processing(self, value):
        if value is None:
            value = exception_processing

        if isinstance(value, string_types):
            value = lookup(value)

        self._exception_processing = value
Beispiel #11
0
    def notification_callback(self, value):
        if value is None:
            value = notification_callback

        if isinstance(value, string_types):
            value = lookup(value)

        self._notification_callback = value
Beispiel #12
0
    def flush_callback(self, value):
        if value is None:
            value = flush_callback

        if isinstance(value, string_types):
            value = lookup(value)

        self._flush_callback = value
Beispiel #13
0
    def write_callback(self, value):
        if value is None:
            value = write_callback

        if isinstance(value, string_types):
            value = lookup(value)

        self._write_callback = value
Beispiel #14
0
    def flush_callback(self, value):
        if value is None:
            value = flush_callback

        if isinstance(value, string_types):
            value = lookup(value)

        self._flush_callback = value
Beispiel #15
0
    def get(self, name):

        if name in _OPERATORS_BY_NAME:
            return _OPERATORS_BY_NAME[name]

        else:
            try:
                return lookup(name)

            except ImportError:
                pass
Beispiel #16
0
    def loadmodules(self, modules=None, rel=None):
        """ry to (re)load modules and return loaded modules.

        :param modules: list of module (name) to load.
        :param bool rel: flag for forcing reload of module. Default is this
            rel flag (false by default).
        :rtype: list
        :return: loaded modules."""

        result = []

        if rel is None:
            rel = self.rel

        if modules is None:
            modules = self._modules

        for module in modules:

            if isinstance(module, string_types):
                name = module
                module = lookup(name)

            elif isinstance(module, ModuleType):
                name = module.__name__

            else:
                raise TypeError(
                    'wrong value {0} in {1}. List of str/module expected.'
                    .format(
                        module, modules
                    )
                )

            if not rel and module in self._loadedmodules:
                continue

            reload_module(module)
            result.append(module)
            self._loadedmodules.add(module)

        return result
Beispiel #17
0
    def _load_drivers(self, drivers):
        result = []

        for module in drivers:
            if isinstance(module, string_types):
                try:
                    module = lookup(module)

                except ImportError as err:
                    raise_from(
                        ValueError(
                            'Impossible to load module: {0}'.format(module)
                        ),
                        err
                    )

            elif not isinstance(module, ModuleType):
                raise TypeError(
                    'Expected module or string, got: {0}'.format(type(module))
                )

            result.append(module)

        return result
Beispiel #18
0
    def _getparams_rtype(cls, function):
        """Get function params from input function and rtype.

        :return: OrderedDict, rtype, vargs and kwargs.
        :rtype: tuple
        """
        try:
            args, vargs, kwargs, default = getargspec(function)

        except TypeError:
            args, vargs, kwargs, default = (), (), (), ()

        indexlen = len(args) - (0 if default is None else len(default))

        params = OrderedDict()

        for index, arg in enumerate(args):

            pkwargs = {'name': arg, 'mandatory': True}  # param kwargs

            if index >= indexlen:  # has default value
                value = default[index - indexlen]
                pkwargs['default'] = value
                pkwargs['ref'] = None if value is None else data2schema(value)
                pkwargs['mandatory'] = False

            params[arg] = pkwargs

        rtype = None

        # parse docstring
        if function.__doc__ is not None and not isbuiltin(function):

            scope = get_function_globals(function)

            for match in cls._REC.findall(function.__doc__):
                if rtype is None:
                    rrtype = match[4].strip() or None

                    if rrtype:

                        rtypes = rrtype.split(',')

                        schemas = []
                        for rtype_ in rtypes:

                            rtype_ = rtype_.strip()
                            islist = False

                            try:
                                lkrtype = lookup(rtype_, scope=scope)

                            except ImportError:
                                islist = True

                                try:
                                    if rtype_[-1] == 's':
                                        lkrtype = lookup(rtype_[:-1],
                                                         scope=scope)

                                    elif rtype_.startswith('list of '):
                                        lkrtype = lookup(rtype_[8:],
                                                         scope=scope)

                                    else:
                                        raise

                                except ImportError:
                                    msg = 'rtype "{0}" ({1}) from {2} not found.'
                                    raise ImportError(
                                        msg.format(rtype_, rrtype, function))

                            try:
                                schemacls = datatype2schemacls(lkrtype)

                            except TypeError:
                                schemacls = ParamTypeSchema(type=lkrtype)

                            rschema = schemacls()

                            if islist:
                                rschema = ArraySchema(itemtype=rschema)

                            schemas.append(rschema)

                        if len(rtypes) > 1:
                            rtype = OneOfSchema(schemas=schemas, nullable=True)

                        else:
                            rtype = schemas[0]

                        continue

                pname = (match[1] or match[2]).strip()

                if pname and pname in params:

                    ptype = (match[0] or match[3]).strip()

                    ptypes = ptype.split(',')

                    schemas = []

                    for ptype in ptypes:

                        ptype = ptype.strip()

                        islist = False

                        try:
                            lkptype = lookup(ptype, scope=scope)

                        except ImportError:
                            islist = True

                            try:
                                if ptype[-1] == 's':
                                    lkptype = lookup(ptype[:-1], scope=scope)

                                elif ptype.startswith('list of '):
                                    lkptype = lookup(ptype[8:], scope=scope)

                                else:
                                    raise

                            except ImportError:

                                msg = 'Error on ptype "{0}" ({1}) from {2} not found.'
                                raise ImportError(
                                    msg.format(pname, ptype, function))

                        try:
                            schemacls = datatype2schemacls(lkptype)

                        except TypeError:
                            schemacls = ParamTypeSchema(type=lkptype)

                        pschema = schemacls()

                        if islist:
                            pschema = ArraySchema(itemtype=pschema)

                        schemas.append(pschema)

                    if len(ptypes) > 1:
                        pschema = OneOfSchema(schemas=schemas, nullable=True)

                    else:
                        pschema = schemas[0]

                    params[pname]['ref'] = pschema

        return params, rtype, vargs, kwargs
Beispiel #19
0
    def _getparams_rtype(cls, function):
        """Get function params from input function and rtype.

        :return: OrderedDict, rtype, vargs and kwargs.
        :rtype: tuple
        """
        try:
            args, vargs, kwargs, default = getargspec(function)

        except TypeError:
            args, vargs, kwargs, default = (), (), (), ()

        indexlen = len(args) - (0 if default is None else len(default))

        params = OrderedDict()

        for index, arg in enumerate(args):

            pkwargs = {
                'name': arg,
                'mandatory': True
            }  # param kwargs

            if index >= indexlen:  # has default value
                value = default[index - indexlen]
                pkwargs['default'] = value
                pkwargs['ref'] = None if value is None else data2schema(value)
                pkwargs['mandatory'] = False

            params[arg] = pkwargs

        rtype = None

        # parse docstring
        if function.__doc__ is not None and not isbuiltin(function):

            scope = get_function_globals(function)

            for match in cls._REC.findall(function.__doc__):
                if rtype is None:
                    rrtype = match[4].strip() or None

                    if rrtype:

                        rtypes = rrtype.split(',')

                        schemas = []
                        for rtype_ in rtypes:

                            rtype_ = rtype_.strip()
                            islist = False

                            try:
                                lkrtype = lookup(rtype_, scope=scope)

                            except ImportError:
                                islist = True

                                try:
                                    if rtype_[-1] == 's':
                                        lkrtype = lookup(
                                            rtype_[:-1], scope=scope
                                        )

                                    elif rtype_.startswith('list of '):
                                        lkrtype = lookup(
                                            rtype_[8:], scope=scope
                                        )

                                    else:
                                        raise

                                except ImportError:
                                    msg = 'rtype "{0}" ({1}) from {2} not found.'
                                    raise ImportError(
                                        msg.format(rtype_, rrtype, function)
                                    )

                            try:
                                schemacls = datatype2schemacls(lkrtype)

                            except TypeError:
                                schemacls = ParamTypeSchema(type=lkrtype)

                            rschema = schemacls()

                            if islist:
                                rschema = ArraySchema(itemtype=rschema)

                            schemas.append(rschema)

                        if len(rtypes) > 1:
                            rtype = OneOfSchema(schemas=schemas, nullable=True)

                        else:
                            rtype = schemas[0]

                        continue

                pname = (match[1] or match[2]).strip()

                if pname and pname in params:

                    ptype = (match[0] or match[3]).strip()

                    ptypes = ptype.split(',')

                    schemas = []

                    for ptype in ptypes:

                        ptype = ptype.strip()

                        islist = False

                        try:
                            lkptype = lookup(ptype, scope=scope)

                        except ImportError:
                            islist = True

                            try:
                                if ptype[-1] == 's':
                                    lkptype = lookup(ptype[:-1], scope=scope)

                                elif ptype.startswith('list of '):
                                    lkptype = lookup(ptype[8:], scope=scope)

                                else:
                                    raise

                            except ImportError:

                                msg = 'Error on ptype "{0}" ({1}) from {2} not found.'
                                raise ImportError(
                                    msg.format(pname, ptype, function)
                                )

                        try:
                            schemacls = datatype2schemacls(lkptype)

                        except TypeError:
                            schemacls = ParamTypeSchema(type=lkptype)

                        pschema = schemacls()

                        if islist:
                            pschema = ArraySchema(itemtype=pschema)

                        schemas.append(pschema)

                    if len(ptypes) > 1:
                        pschema = OneOfSchema(schemas=schemas, nullable=True)

                    else:
                        pschema = schemas[0]

                    params[pname]['ref'] = pschema

        return params, rtype, vargs, kwargs
Beispiel #20
0
    def dispatch(self, req, resp):
        """
        Dispatch request to handler, which will fill response.

        :param req: request object
        :type req: link.wsgi.req.Request

        :param resp: response object
        :type resp: link.wsgi.resp.Response
        """

        for urlpattern in self.urlpatterns:
            # check URL for every configured patterns
            if match(urlpattern, req.path) is not None:
                self.logger.debug('URLPattern({0})'.format(urlpattern))
                route = self.urlpatterns[urlpattern]

                # check if request method is allowed for route
                if req.method in route:
                    try:
                        h = hash('{0}{1}'.format(urlpattern, req.method))

                        # check if handler has already been instantiated
                        if h not in self.objcache:
                            # fetch handler, instantiate it if it's a class
                            handler = lookup(route[req.method])

                            if isclass(handler):
                                # the handler for a class is a method
                                # the method's name is the request method
                                handler = getattr(
                                    handler(),
                                    req.method.lower()
                                )

                            self.objcache[h] = handler

                        else:
                            handler = self.objcache[h]

                        # instantiate middlewares if needed
                        middlewares = []

                        for middleware in self.middlewares:
                            h = hash(middleware)

                            if h not in self.objcache:
                                self.objcache[h] = lookup(middleware)()

                            middlewares.append(self.objcache[h])

                        # apply middlewares on request/response/handler
                        abort = False
                        for middleware in middlewares:
                            if middleware.before(req, resp, handler):
                                abort = True
                                break

                        # if a middleware returned True, the request is aborted
                        if abort:
                            self.logger.debug('Request aborted')
                            break

                        # pass request/response to the handler
                        handler(req, resp)

                        # apply middlewares on request/response/handler again
                        for middleware in reversed(middlewares):
                            if middleware.after(req, resp, handler):
                                break

                    except Exception:
                        # if any error happens, return a 500 internal error
                        resp.status = 500
                        resp.content = traceback.format_exc()

                else:
                    # if the method was not configured for the route, return a
                    # 405 method not allowed
                    resp.status = 405
                    resp.content = 'Unkown method: {0}'.format(req.method)

                # here a handler was found, successfully executed or not
                # we do not need to check for another urlpattern
                break

        else:
            # no urlpattern matched, return a 404 not found
            resp.status = 404
            resp.content = 'No route matching URL: {0}'.format(req.path)
Beispiel #21
0
# -*- coding: utf-8 -*-

from aloe import step, world

from link.kvstore.core import KeyValueStore
from b3j0f.utils.path import lookup
from time import sleep


# make sure driver is registered
lookup('link.riak.driver')


@step(r'I connect to "([^"]*)"')
def connect_to_kvstore(step, uri):
    world.store = KeyValueStore.get_middleware_by_uri(uri)


@step(r'I disconnect from the store')
def disconnect_from_kvstore(step):
    del world.store


@step(r'I wait (\d*) seconds')
def wait(step, seconds):
    sleep(int(seconds))