Python tornado.util.import_object() Examples

The following are 30 code examples of tornado.util.import_object(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tornado.util , or try the search function .
Example #1
Source File: __init__.py    From torngas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _create_cache(backend, **kwargs):
    try:
        # Try to get the CACHES entry for the given backend name first
        try:
            conf = settings.CACHES[backend]
        except KeyError:
            try:
                # Trying to import the given backend, in case it's a dotted path
                import_object(backend)
            except ImportError as e:
                raise InvalidCacheBackendError("Could not find backend '%s': %s" % (
                    backend, e))
            location = kwargs.pop('LOCATION', '')
            params = kwargs
        else:
            params = conf.copy()
            params.update(kwargs)
            backend = params.pop('BACKEND')
            location = params.pop('LOCATION', '')
        backend_cls = import_object(backend)
    except ImportError as e:
        raise InvalidCacheBackendError(
            "Could not find backend '%s': %s" % (backend, e))
    return backend_cls(location, params) 
Example #2
Source File: manager.py    From torngas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def register(self, name):
        if isinstance(name, (str, unicode,)):
            name = import_object(name)
        obj = name()

        if self._ismd(obj, 'process_init'):
            self._INIT_LIST.append(obj.process_init)
        if self._ismd(obj, 'process_call'):
            self._CALL_LIST.appendleft(obj.process_call)
        if self._ismd(obj, 'process_request'):
            self._REQUEST_LIST.appendleft(obj.process_request)
        if self._ismd(obj, 'process_render'):
            self._RENDER_LIST.append(obj.process_render)

        if self._ismd(obj, 'process_response'):
            self._RESPONSE_LIST.append(obj.process_response)

        if self._ismd(obj, 'process_endcall'):
            self._ENDCALL_LIST.append(obj.process_endcall)

        if self._ismd(obj, 'process_exception'):
            self._EXCEPTION_LIST.appendleft(obj.process_exception) 
Example #3
Source File: httpclient.py    From honeything with GNU General Public License v3.0 6 votes vote down vote up
def configure(impl, **kwargs):
        """Configures the AsyncHTTPClient subclass to use.

        AsyncHTTPClient() actually creates an instance of a subclass.
        This method may be called with either a class object or the
        fully-qualified name of such a class (or None to use the default,
        SimpleAsyncHTTPClient)

        If additional keyword arguments are given, they will be passed
        to the constructor of each subclass instance created.  The
        keyword argument max_clients determines the maximum number of
        simultaneous fetch() operations that can execute in parallel
        on each IOLoop.  Additional arguments may be supported depending
        on the implementation class in use.

        Example::

           AsyncHTTPClient.configure("tornado.curl_httpclient.CurlAsyncHTTPClient")
        """
        if isinstance(impl, (unicode, bytes_type)):
            impl = import_object(impl)
        if impl is not None and not issubclass(impl, AsyncHTTPClient):
            raise ValueError("Invalid AsyncHTTPClient implementation")
        AsyncHTTPClient._impl_class = impl
        AsyncHTTPClient._impl_kwargs = kwargs 
Example #4
Source File: webserver.py    From torngas with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _install_application(self, application):
        if not self.urls:
            raise UrlError("urls not found.")
        if application:
            app_class = application
        else:
            app_class = Application

        tornado_conf = settings.TORNADO_CONF
        if 'default_handler_class' in tornado_conf and \
                isinstance(tornado_conf['default_handler_class'], basestring):
            tornado_conf['default_handler_class'] = import_object(tornado_conf['default_handler_class'])

        else:
            tornado_conf['default_handler_class'] = import_object('torngas.handler.ErrorHandler')

        tornado_conf['debug'] = settings.DEBUG
        self.application = app_class(handlers=self.urls,
                                     default_host='',
                                     transforms=None, wsgi=False,
                                     middlewares=settings.MIDDLEWARE_CLASSES,
                                     **tornado_conf) 
Example #5
Source File: routing.py    From teleport with Apache License 2.0 5 votes vote down vote up
def __init__(
        self,
        matcher: "Matcher",
        target: Any,
        target_kwargs: Dict[str, Any] = None,
        name: str = None,
    ) -> None:
        """Constructs a Rule instance.

        :arg Matcher matcher: a `Matcher` instance used for determining
            whether the rule should be considered a match for a specific
            request.
        :arg target: a Rule's target (typically a ``RequestHandler`` or
            `~.httputil.HTTPServerConnectionDelegate` subclass or even a nested `Router`,
            depending on routing implementation).
        :arg dict target_kwargs: a dict of parameters that can be useful
            at the moment of target instantiation (for example, ``status_code``
            for a ``RequestHandler`` subclass). They end up in
            ``target_params['target_kwargs']`` of `RuleRouter.get_target_delegate`
            method.
        :arg str name: the name of the rule that can be used to find it
            in `ReversibleRouter.reverse_url` implementation.
        """
        if isinstance(target, str):
            # import the Module and instantiate the class
            # Must be a fully qualified name (module.ClassName)
            target = import_object(target)

        self.matcher = matcher  # type: Matcher
        self.target = target
        self.target_kwargs = target_kwargs if target_kwargs else {}
        self.name = name 
Example #6
Source File: rediscache.py    From torngas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def connection_pool_class(self):
        cls = self.options.get('POOL_CLASS', 'redis.ConnectionPool')
        mod_path, cls_name = cls.rsplit('.', 1)
        try:
            mod = import_object(mod_path)
            pool_class = getattr(mod, cls_name)
        except (AttributeError, ImportError):
            raise ConfigError("Could not find connection pool class '%s'" % cls)
        return pool_class 
Example #7
Source File: routing.py    From teleport with Apache License 2.0 5 votes vote down vote up
def __init__(self, matcher, target, target_kwargs=None, name=None):
        """Constructs a Rule instance.

        :arg Matcher matcher: a `Matcher` instance used for determining
            whether the rule should be considered a match for a specific
            request.
        :arg target: a Rule's target (typically a ``RequestHandler`` or
            `~.httputil.HTTPServerConnectionDelegate` subclass or even a nested `Router`,
            depending on routing implementation).
        :arg dict target_kwargs: a dict of parameters that can be useful
            at the moment of target instantiation (for example, ``status_code``
            for a ``RequestHandler`` subclass). They end up in
            ``target_params['target_kwargs']`` of `RuleRouter.get_target_delegate`
            method.
        :arg str name: the name of the rule that can be used to find it
            in `ReversibleRouter.reverse_url` implementation.
        """
        if isinstance(target, str):
            # import the Module and instantiate the class
            # Must be a fully qualified name (module.ClassName)
            target = import_object(target)

        self.matcher = matcher  # type: Matcher
        self.target = target
        self.target_kwargs = target_kwargs if target_kwargs else {}
        self.name = name 
Example #8
Source File: ioloop.py    From teleport with Apache License 2.0 5 votes vote down vote up
def configure(
        cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any
    ) -> None:
        if asyncio is not None:
            from tornado.platform.asyncio import BaseAsyncIOLoop

            if isinstance(impl, str):
                impl = import_object(impl)
            if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):
                raise RuntimeError(
                    "only AsyncIOLoop is allowed when asyncio is available"
                )
        super(IOLoop, cls).configure(impl, **kwargs) 
Example #9
Source File: routing.py    From teleport with Apache License 2.0 5 votes vote down vote up
def __init__(
        self,
        matcher: "Matcher",
        target: Any,
        target_kwargs: Dict[str, Any] = None,
        name: str = None,
    ) -> None:
        """Constructs a Rule instance.

        :arg Matcher matcher: a `Matcher` instance used for determining
            whether the rule should be considered a match for a specific
            request.
        :arg target: a Rule's target (typically a ``RequestHandler`` or
            `~.httputil.HTTPServerConnectionDelegate` subclass or even a nested `Router`,
            depending on routing implementation).
        :arg dict target_kwargs: a dict of parameters that can be useful
            at the moment of target instantiation (for example, ``status_code``
            for a ``RequestHandler`` subclass). They end up in
            ``target_params['target_kwargs']`` of `RuleRouter.get_target_delegate`
            method.
        :arg str name: the name of the rule that can be used to find it
            in `ReversibleRouter.reverse_url` implementation.
        """
        if isinstance(target, str):
            # import the Module and instantiate the class
            # Must be a fully qualified name (module.ClassName)
            target = import_object(target)

        self.matcher = matcher  # type: Matcher
        self.target = target
        self.target_kwargs = target_kwargs if target_kwargs else {}
        self.name = name 
Example #10
Source File: ioloop.py    From teleport with Apache License 2.0 5 votes vote down vote up
def configure(
        cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any
    ) -> None:
        if asyncio is not None:
            from tornado.platform.asyncio import BaseAsyncIOLoop

            if isinstance(impl, str):
                impl = import_object(impl)
            if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):
                raise RuntimeError(
                    "only AsyncIOLoop is allowed when asyncio is available"
                )
        super(IOLoop, cls).configure(impl, **kwargs) 
Example #11
Source File: base.py    From torngas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_key_func(key_func):
    """
    Function to decide which key function to use.

    Defaults to ``default_key_func``.
    """
    if key_func is not None:
        if callable(key_func):
            return key_func
        else:
            return import_object(key_func)
    return default_key_func 
Example #12
Source File: routing.py    From pySINDy with MIT License 5 votes vote down vote up
def __init__(self, matcher, target, target_kwargs=None, name=None):
        """Constructs a Rule instance.

        :arg Matcher matcher: a `Matcher` instance used for determining
            whether the rule should be considered a match for a specific
            request.
        :arg target: a Rule's target (typically a ``RequestHandler`` or
            `~.httputil.HTTPServerConnectionDelegate` subclass or even a nested `Router`,
            depending on routing implementation).
        :arg dict target_kwargs: a dict of parameters that can be useful
            at the moment of target instantiation (for example, ``status_code``
            for a ``RequestHandler`` subclass). They end up in
            ``target_params['target_kwargs']`` of `RuleRouter.get_target_delegate`
            method.
        :arg str name: the name of the rule that can be used to find it
            in `ReversibleRouter.reverse_url` implementation.
        """
        if isinstance(target, str):
            # import the Module and instantiate the class
            # Must be a fully qualified name (module.ClassName)
            target = import_object(target)

        self.matcher = matcher  # type: Matcher
        self.target = target
        self.target_kwargs = target_kwargs if target_kwargs else {}
        self.name = name 
Example #13
Source File: util_test.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def test_import_member(self):
        self.assertIs(import_object('tornado.escape.utf8'), utf8) 
Example #14
Source File: util_test.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def test_import_member_unicode(self):
        self.assertIs(import_object(u('tornado.escape.utf8')), utf8) 
Example #15
Source File: util_test.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def test_import_module(self):
        self.assertIs(import_object('tornado.escape'), tornado.escape) 
Example #16
Source File: util_test.py    From EventGhost with GNU General Public License v2.0 5 votes vote down vote up
def test_import_module_unicode(self):
        # The internal implementation of __import__ differs depending on
        # whether the thing being imported is a module or not.
        # This variant requires a byte string in python 2.
        self.assertIs(import_object(u('tornado.escape')), tornado.escape) 
Example #17
Source File: ioloop.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def configure(
        cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any
    ) -> None:
        if asyncio is not None:
            from tornado.platform.asyncio import BaseAsyncIOLoop

            if isinstance(impl, str):
                impl = import_object(impl)
            if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):
                raise RuntimeError(
                    "only AsyncIOLoop is allowed when asyncio is available"
                )
        super(IOLoop, cls).configure(impl, **kwargs) 
Example #18
Source File: routing.py    From V1EngineeringInc-Docs with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
def __init__(
        self,
        matcher: "Matcher",
        target: Any,
        target_kwargs: Dict[str, Any] = None,
        name: str = None,
    ) -> None:
        """Constructs a Rule instance.

        :arg Matcher matcher: a `Matcher` instance used for determining
            whether the rule should be considered a match for a specific
            request.
        :arg target: a Rule's target (typically a ``RequestHandler`` or
            `~.httputil.HTTPServerConnectionDelegate` subclass or even a nested `Router`,
            depending on routing implementation).
        :arg dict target_kwargs: a dict of parameters that can be useful
            at the moment of target instantiation (for example, ``status_code``
            for a ``RequestHandler`` subclass). They end up in
            ``target_params['target_kwargs']`` of `RuleRouter.get_target_delegate`
            method.
        :arg str name: the name of the rule that can be used to find it
            in `ReversibleRouter.reverse_url` implementation.
        """
        if isinstance(target, str):
            # import the Module and instantiate the class
            # Must be a fully qualified name (module.ClassName)
            target = import_object(target)

        self.matcher = matcher  # type: Matcher
        self.target = target
        self.target_kwargs = target_kwargs if target_kwargs else {}
        self.name = name 
Example #19
Source File: routing.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def __init__(
        self,
        matcher: "Matcher",
        target: Any,
        target_kwargs: Dict[str, Any] = None,
        name: str = None,
    ) -> None:
        """Constructs a Rule instance.

        :arg Matcher matcher: a `Matcher` instance used for determining
            whether the rule should be considered a match for a specific
            request.
        :arg target: a Rule's target (typically a ``RequestHandler`` or
            `~.httputil.HTTPServerConnectionDelegate` subclass or even a nested `Router`,
            depending on routing implementation).
        :arg dict target_kwargs: a dict of parameters that can be useful
            at the moment of target instantiation (for example, ``status_code``
            for a ``RequestHandler`` subclass). They end up in
            ``target_params['target_kwargs']`` of `RuleRouter.get_target_delegate`
            method.
        :arg str name: the name of the rule that can be used to find it
            in `ReversibleRouter.reverse_url` implementation.
        """
        if isinstance(target, str):
            # import the Module and instantiate the class
            # Must be a fully qualified name (module.ClassName)
            target = import_object(target)

        self.matcher = matcher  # type: Matcher
        self.target = target
        self.target_kwargs = target_kwargs if target_kwargs else {}
        self.name = name 
Example #20
Source File: util_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_import_member_unicode(self):
        self.assertIs(import_object(u('tornado.escape.utf8')), utf8) 
Example #21
Source File: util_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_import_module(self):
        self.assertIs(import_object('tornado.escape'), tornado.escape) 
Example #22
Source File: util_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_import_module_unicode(self):
        # The internal implementation of __import__ differs depending on
        # whether the thing being imported is a module or not.
        # This variant requires a byte string in python 2.
        self.assertIs(import_object(u('tornado.escape')), tornado.escape) 
Example #23
Source File: util_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_import_member(self):
        self.assertIs(import_object('tornado.escape.utf8'), utf8) 
Example #24
Source File: util_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_import_module(self):
        self.assertIs(import_object('tornado.escape'), tornado.escape) 
Example #25
Source File: util_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_import_module_unicode(self):
        # The internal implementation of __import__ differs depending on
        # whether the thing being imported is a module or not.
        # This variant requires a byte string in python 2.
        self.assertIs(import_object(u('tornado.escape')), tornado.escape) 
Example #26
Source File: ioloop.py    From opendevops with GNU General Public License v3.0 5 votes vote down vote up
def configure(
        cls, impl: "Union[None, str, Type[Configurable]]", **kwargs: Any
    ) -> None:
        if asyncio is not None:
            from tornado.platform.asyncio import BaseAsyncIOLoop

            if isinstance(impl, str):
                impl = import_object(impl)
            if isinstance(impl, type) and not issubclass(impl, BaseAsyncIOLoop):
                raise RuntimeError(
                    "only AsyncIOLoop is allowed when asyncio is available"
                )
        super(IOLoop, cls).configure(impl, **kwargs) 
Example #27
Source File: util_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_import_member(self):
        self.assertIs(import_object('tornado.escape.utf8'), utf8) 
Example #28
Source File: webserver.py    From torngas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_application(self, application=None):
        """

        :type application: torngas.application.Application subclass or instance
        :return:
        """
        self._patch_httpserver()
        if settings.TRANSLATIONS:
            try:
                from tornado import locale

                locale.load_translations(settings.TRANSLATIONS_CONF.translations_dir)
            except:
                warnings.warn('locale dir load failure,maybe your config file is not set correctly.')

        if not application:
            self._install_application(application)
        elif isinstance(application, Application):
            self.application = application
        elif issubclass(application, Application):
            self._install_application(application)
        else:
            raise ArgumentError('need torngas.application.Application instance object or subclass.')

        tmpl = settings.TEMPLATE_CONFIG.template_engine
        self.application.tmpl = import_object(tmpl) if tmpl else None

        return self.application 
Example #29
Source File: webserver.py    From torngas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_urls(self):
        urls = []
        if settings.INSTALLED_APPS:
            for app_name in settings.INSTALLED_APPS:
                app_urls = import_object(app_name + '.urls.urls')
                urls.extend(app_urls)
        else:
            raise ConfigError('load urls error,INSTALLED_APPS not found!')
        self.urls = urls
        return self.urls 
Example #30
Source File: utils.py    From torngas with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __getattr__(self, func_name):
        if self.module is None:
            self.module = import_object(self.module_name)
        return getattr(self.module, func_name)