• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python werkzeug.import_string函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中werkzeug.import_string函数的典型用法代码示例。如果您正苦于以下问题:Python import_string函数的具体用法?Python import_string怎么用?Python import_string使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了import_string函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: profile_execute

def profile_execute(p_id):
    data = Profile().find_by_pk(p_id)
    source = data['source']
    destination = data['destination']
    data = data['profile']
    split = int(data.get('split_size') or 0)
    
    """ Dumping from Source """
    SourceAct = import_string(source.get('provider') + '.model.SourceAct')
    src_act = SourceAct(**source)
    file_name = src_act.dump_zipped()
    
    """ Output file name """
    dt_utc = datetime.utcnow().strftime('%Y_%m_%d_%H-%M-%S')
    out = 'wb_' + functions.clean_str(data['title']) + dt_utc + functions.ext_file(file_name)
    
    if split > 0:
        cmd = "split -b %sm %s /tmp/%s" % (split, file_name, out)
        subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
    """ Executing destination part  """
    DestinationAct = import_string(destination.get('provider') + '.model.DestinationAct')
    dst_act = DestinationAct(**destination)
    if split == 0:
        dst_act.upload_file(file_name, out)
    elif split > 0:
        dst_act.mkdir(dt_utc)
        dst_act.cd(dt_utc)
        for f in os.listdir('/tmp'):
            if f.startswith(out):
                dst_act.upload_file('/tmp/%s' % f, f)
        os.unlink(file_name)
    
    return data
开发者ID:inabhi9,项目名称:webackup,代码行数:34,代码来源:model.py


示例2: load

    def load(self):
        """Load all the installed packages.
        """
        if self.loaded:
            return

        from kalapy.web.package import Package

        self.lock.acquire()
        try:
            for package in settings.INSTALLED_PACKAGES:
                if package in self.packages:
                    continue
                logger.info(' * Loading package: %s' % package)
                if package not in sys.modules:
                    import_string(package)

                self.packages[package] = Package(package)

                self.load_modules(package, 'models')
                self.load_modules(package, 'views')

            self.loaded = True
        finally:
            self.lock.release()
开发者ID:garyyeap,项目名称:zoe-robot,代码行数:25,代码来源:pool.py


示例3: set_blueprints

def set_blueprints(app, blueprints):
    """
    Registers blueprints with the app.
    """
    # Register blueprints.
    for blueprint in blueprints:
        url_prefix = None
        if len(blueprint) == 2:
            blueprint, url_prefix = blueprint
        blueprint_object = import_string('%s:BLUEPRINT' % blueprint, silent=True)
        blueprint_name, blueprint_import_name = blueprint.split('.')[-1], blueprint
        if not blueprint_object:
            options = dict(static_folder='static', template_folder='templates')
            blueprint_object = Blueprint(blueprint_name, blueprint_import_name, **options)
        blueprint_routes = import_string('%s.urls:routes' % blueprint_import_name, silent=True)
        if blueprint_routes:
            urls.set_urls(blueprint_object, blueprint_routes)

        # Other initializations.
        for fn, values in [(set_before_handlers, import_string('%s:BEFORE_REQUESTS' % blueprint, silent=True)),
                           (set_before_app_handlers, import_string('%s:BEFORE_APP_REQUESTS' % blueprint, silent=True)),
                           (set_after_handlers, import_string('%s:AFTER_REQUESTS' % blueprint, silent=True)),
                           (set_after_app_handlers, import_string('%s:AFTER_APP_REQUESTS' % blueprint, silent=True)),
                           (set_context_processors, import_string('%s:CONTEXT_PROCESSORS' % blueprint, silent=True)),
                           (set_app_context_processors, import_string('%s:APP_CONTEXT_PROCESSORS' % blueprint, silent=True)),
                           (set_error_handlers, import_string('%s:ERROR_HANDLERS' % blueprint, silent=True)),
                           (set_app_error_handlers, import_string('%s:APP_ERROR_HANDLERS' % blueprint, silent=True))]:
            if values:
                fn(blueprint_object, values)
        # Can be mounted at specific prefix.
        if url_prefix:
            app.register_blueprint(blueprint_object, url_prefix=url_prefix)
        else:
            app.register_blueprint(blueprint_object)
开发者ID:Mondego,项目名称:pyreco,代码行数:34,代码来源:allPythonContent.py


示例4: db_create_models

def db_create_models():
    "Creates database tables."
    # db_createall doesn't work if the models aren't imported
    import_string('models', silent=True)
    for blueprint_name, blueprint in app.blueprints.iteritems():
        import_string('%s.models' % blueprint.import_name, silent=True)
    db.create_all()
开发者ID:Mondego,项目名称:pyreco,代码行数:7,代码来源:allPythonContent.py


示例5: configure_template_filters

def configure_template_filters(app):
    """Configure filters and tags for jinja"""

    app.jinja_env.filters['nl2br'] = import_string('utils.templates.nl2br')
    app.jinja_env.filters['dateformat'] = import_string('utils.templates.dateformat')
    app.jinja_env.filters['timeformat'] = import_string('utils.templates.timeformat')
    app.jinja_env.filters['datetimeformat'] = import_string('utils.templates.datetimeformat')
开发者ID:Invoicy,项目名称:invoicy,代码行数:7,代码来源:main.py


示例6: db_dropall

def db_dropall():
    "Drops all database tables"
    # db_dropall doesn't work if the models aren't imported
    import_string('models', silent=True)
    for blueprint_name, blueprint in app.blueprints.iteritems():
        import_string('%s.models' % blueprint.import_name, silent=True)
    db.drop_all()
开发者ID:Mondego,项目名称:pyreco,代码行数:7,代码来源:allPythonContent.py


示例7: get_view

def get_view(endpoint):
  try:
    return import_string('catonmat.views.' + endpoint)
  except (ImportError, AttributeError):
    try:
      return import_string(endpoint)
    except (ImportError, AttributeError):
      raise RuntimeError('Could not locate view for %r' % endpoint)
开发者ID:gobburms,项目名称:catonmat.net,代码行数:8,代码来源:utils.py


示例8: build_suite

def build_suite(name):
    """Build test suite for the given name. A name can be either a package name
    or a fully qualified name of the test class or a specific test method within
    a package prefixed with ``package_name:``.

    For example:

        >>> build_suite('hello')
        >>> build_suite('hello:HelloTest')
        >>> build_suite('hello:HelloTest.test_hello')
        >>> build_suite('foo:foo.FooTest')
        >>> build_suite('foo:bar.BarTest')

    :returns:
        an instance of `TestSuite`
    """
    try:
        package, test = name.split(':')
    except:
        package, test = name, None

    test_module = '%s.%s' % (package, TEST_MODULE)
    test_fullname = '%s.%s' % (test_module, test) if test else test_module

    suite = unittest.TestSuite()

    match = re.match('(.*?)\.(test_\w+)$', test_fullname)
    if match:
        try:
            TestClass = import_string(match.group(1))
        except ImportError:
            raise ImportError(match.group(1))
        suite.addTest(TestClass(match.group(2)))

    elif test:
        try:
            TestClass = import_string(test_fullname)
        except AttributeError:
            raise AttributeError(test_fullname)
        if isinstance(TestClass, unittest.TestCase.__class__):
            suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestClass))
        else:
            suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(TestClass))

    else:
        try:
            test_modules = list(find_modules(test_module))
        except ValueError:
            test_modules = [test_module]
        for module in map(import_string, test_modules):
            suite.addTest(unittest.defaultTestLoader.loadTestsFromModule(module))

    return suite
开发者ID:cloudappsetup,项目名称:kalapy,代码行数:53,代码来源:utils.py


示例9: get_view

def get_view(endpoint):
    """Returns the view for the endpoint.  It will cache both positive and
    negative hits, so never pass untrusted values to it.  If a view does
    not exist, `None` is returned.
    """
    view = _resolved_views.get(endpoint)
    if view is not None:
        return view
    try:
        view = import_string('rater.views.' + endpoint)
    except (ImportError, AttributeError):
        view = import_string(endpoint, silent=True)
    _resolved_views[endpoint] = view
    return view
开发者ID:amadev,项目名称:rater,代码行数:14,代码来源:application.py


示例10: configure_blueprints

def configure_blueprints(app, blueprints):
    blueprints_list = []
    packages_list = []

    for name in blueprints:
        blueprint = import_string(name)
        blueprints_list.append(blueprint)
        package = import_string(blueprint.import_name)
        packages_list.append(package)

    for package in list(set(packages_list)):
        __import__('%s.views' % package.__name__)

    for blueprint in list(set(blueprints_list)):
        app.register_blueprint(blueprint)
开发者ID:OctavianLee,项目名称:fleur-de-lis,代码行数:15,代码来源:__init__.py


示例11: load_middleware

    def load_middleware(self, classes):
        """Returns a dictionary of middleware instance methods for a list of
        classes.

        :param classes:
            A list of middleware classes.
        :return:
            A dictionary with middleware instance methods.
        """
        res = {}

        for cls in classes:
            if isinstance(cls, basestring):
                id = cls
            else:
                id = cls.__module__ + '.' + cls.__name__

            if id not in self.methods:
                if isinstance(cls, basestring):
                    cls = import_string(cls)

                obj = cls()
                self.instances[id] = obj
                self.methods[id] = [getattr(obj, n, None) for n in self.names]

            for name, method in zip(self.names, self.methods[id]):
                if method:
                    res.setdefault(name, []).append(method)

        for name in self.reverse_names:
            if name in res:
                res[name].reverse()

        return res
开发者ID:cconger,项目名称:BuildCraft,代码行数:34,代码来源:__init__.py


示例12: __getitem__

    def __getitem__(self, module):
        """Returns the configuration for a module. If it is not already
        set, loads a ``default_config`` variable from the given module and
        updates the configuration with those default values

        Every module that allows some kind of configuration sets a
        ``default_config`` global variable that is loaded by this function,
        cached and used in case the requested configuration was not defined
        by the user.

        :param module:
            The module name.
        :returns:
            A configuration value.
        """
        if module not in self.loaded:
            # Load default configuration and update config.
            values = import_string(module + '.default_config', silent=True)
            if values:
                self.setdefault(module, values)

            self.loaded.append(module)

        try:
            return dict.__getitem__(self, module)
        except KeyError:
            raise KeyError('Module %r is not configured.' % module)
开发者ID:acettt,项目名称:yandex,代码行数:27,代码来源:config.py


示例13: _load

def _load(Obj,lister, force=False):
	for obj in lister:
		name = NotGiven
		doc = NotGiven
		if isinstance(obj,(list,tuple)):
			if len(obj) > 2:
				doc = obj[2]
			name = obj[1]
			obj = obj[0]
		if isinstance(obj,string_types):
			obj = import_string(obj)
			if name is NotGiven:
				name = getattr(obj,'NAME',name)
			if doc is NotGiven:
				doc = getattr(obj,'DOC',doc)
		
		path = obj.__module__+'.'+obj.__name__
		try:
			obj = Obj.q.get_by(path=path)
		except NoData:
			if name is NotGiven:
				name = path
			obj = Obj.new(name=name, path=path)
		else:
			_upd(obj,(('name',name),('doc',doc)), force=force)

		add_vars(getattr(obj.mod,'VAR',()),obj, force=force)
		add_templates(getattr(obj.mod,'TEMPLATE',()), parent=obj, force=force)
开发者ID:smurfix,项目名称:pybble,代码行数:28,代码来源:add.py


示例14: add_objtypes

def add_objtypes(objects, force=False):
	"""Add a list of MIME types."""

	objs = []
	for obj in objects:
		name = NotGiven
		doc = NotGiven
		if isinstance(obj,(list,tuple)):
			if len(obj) > 2:
				doc = obj[2]
			name = obj[1]
			obj = obj[0]
		if isinstance(obj,string_types):
			obj = import_string(obj)
			if name is NotGiven:
				name = getattr(obj,'NAME',name)
			if doc is NotGiven:
				doc = getattr(obj,'DOC',doc)

		objs.append((obj,name,doc))

	db.create_all()
	try:
		root = root_site.add_default_permissions
	except NoData:
		return

	for obj,name,doc in objs:
		obj = ObjType.get(obj) # will create the record
		_upd(obj,(('name',name),('doc',doc)), force=force)
		if obj._is_new or force:
			root(obj)
开发者ID:smurfix,项目名称:pybble,代码行数:32,代码来源:add.py


示例15: auth_user_model

    def auth_user_model(self):
        """Returns the configured user model.

        :returns:
            A :class:`tipfy.ext.auth.model.User` class.
        """
        return import_string(self.app.get_config(__name__, 'user_model'))
开发者ID:acettt,项目名称:yandex,代码行数:7,代码来源:__init__.py


示例16: dispatch

    def dispatch(self, request):
        """Dispatches a request. This instantiates and calls a
        :class:`tipfy.RequestHandler` based on the matched :class:`Rule`.

        :param request:
            A :class:`tipfy.Request` instance.
        :param match:
            A tuple ``(rule, rule_args)`` with the matched rule and rule
            arguments.
        :param method:
            A method to be used instead of using the request or handler method.
        :returns:
            A :class:`tipfy.Response` instance.
        """
        rule, rule_args = self.match(request)
        handler = rule.handler
        if isinstance(handler, basestring):
            if handler not in self.handlers:
                self.handlers[handler] = import_string(handler)

            rule.handler = handler = self.handlers[handler]

        rv = local.current_handler = handler(request)
        if not isinstance(rv, BaseResponse) and hasattr(rv, '__call__'):
            # If it is a callable but not a response, we call it again.
            rv = rv()

        return rv
开发者ID:aswadrangnekar,项目名称:tipfy,代码行数:28,代码来源:routing.py


示例17: _set_cache

    def _set_cache(self, app, config):
        import_me = config['CACHE_TYPE']
        if '.' not in import_me:
            from . import backends

            try:
                cache_obj = getattr(backends, import_me)
            except AttributeError:
                raise ImportError("%s is not a valid FlaskCache backend" % (
                                  import_me))
        else:
            cache_obj = import_string(import_me)

        cache_args = config['CACHE_ARGS'][:]
        cache_options = {'default_timeout': config['CACHE_DEFAULT_TIMEOUT']}

        if config['CACHE_OPTIONS']:
            cache_options.update(config['CACHE_OPTIONS'])

        if not hasattr(app, 'extensions'):
            app.extensions = {}

        app.extensions.setdefault('cache', {})
        app.extensions['cache'][self] = cache_obj(
                app, config, cache_args, cache_options)
开发者ID:pnordahl,项目名称:flask-cache,代码行数:25,代码来源:__init__.py


示例18: find_related_modules

def find_related_modules(package, related_name_re='.+',
                         ignore_exceptions=False):
    """Find matching modules using a package and a module name pattern."""
    warnings.warn('find_related_modules has been deprecated.',
                  DeprecationWarning)
    package_elements = package.rsplit(".", 1)
    try:
        if len(package_elements) == 2:
            pkg = __import__(package_elements[0], globals(), locals(), [
                             package_elements[1]])
            pkg = getattr(pkg, package_elements[1])
        else:
            pkg = __import__(package_elements[0], globals(), locals(), [])
        pkg_path = pkg.__path__
    except AttributeError:
        return []

    # Find all modules named according to related_name
    p = re.compile(related_name_re)
    modules = []

    for name in find_modules(package, include_packages=True):
        if p.match(name.split('.')[-1]):
            try:
                modules.append(import_string(name, silent=ignore_exceptions))
            except Exception as e:
                if not ignore_exceptions:
                    raise e

    return modules
开发者ID:jalavik,项目名称:invenio-utils,代码行数:30,代码来源:__init__.py


示例19: obj_or_import_string

def obj_or_import_string(value, default=None):
    """Import string or return object."""
    if isinstance(value, string_types):
        return import_string(value)
    elif value:
        return value
    return default
开发者ID:inspirehep,项目名称:invenio-workflows-ui,代码行数:7,代码来源:utils.py


示例20: i18n_store_class

    def i18n_store_class(self):
        """Returns the configured auth store class.

        :returns:
            An auth store class.
        """
        return import_string(self.config["tipfy"]["i18n_store_class"])
开发者ID:peper,项目名称:tipfy,代码行数:7,代码来源:app.py



注:本文中的werkzeug.import_string函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python werkzeug.parse_options_header函数代码示例发布时间:2022-05-26
下一篇:
Python werkzeug.generate_password_hash函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap