当前位置: 首页>>代码示例>>Python>>正文


Python werkzeug.import_string函数代码示例

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


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


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