我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用werkzeug.utils.import_string()。
def get_content_formats(instances=False): content_formats = app.config.get( 'CONTENT_FORMATS', { 'markdown': { 'choice_text': 'Markdown', 'help_text': 'Markdown text editor', 'content_format_class': 'quokka.core.content.formats.MarkdownFormat' } } ) if instances: for _, data in content_formats: data['content_format_instance'] = import_string( data['content_format_class'] )() return content_formats
def parse_config(obj): """ Parses given config either from a file or from an object. Method borrowed from Flask. :param obj: The config to parse. :type obj: any :return: A dictionary containing the parsed Flask config :rtype: dict """ config = {} if isinstance(obj, (str, unicode)): obj = import_string(obj) for key in dir(obj): if key.isupper(): config[key] = getattr(obj, key) return config
def dispatch_url(self, url_string): url, url_adapter, query_args = self.parse_url(url_string) try: endpoint, kwargs = url_adapter.match() except NotFound: raise NotSupported(url_string) except RequestRedirect as e: new_url = "{0.new_url}?{1}".format(e, url_encode(query_args)) return self.dispatch_url(new_url) try: handler = import_string(endpoint) request = Request(url=url, args=query_args) return handler(request, **kwargs) except RequestRedirect as e: return self.dispatch_url(e.new_url)
def xml(self): """Get an etree if possible.""" if 'xml' not in self.mimetype: raise AttributeError( 'Not a XML response (Content-Type: %s)' % self.mimetype) for module in ['xml.etree.ElementTree', 'ElementTree', 'elementtree.ElementTree']: etree = import_string(module, silent=True) if etree is not None: return etree.XML(self.body) raise RuntimeError('You must have ElementTree installed ' 'to use TestResponse.xml')
def main(): '''A simple command-line interface for :py:func:`run_simple`.''' # in contrast to argparse, this works at least under Python < 2.7 import optparse from werkzeug.utils import import_string parser = optparse.OptionParser( usage='Usage: %prog [options] app_module:app_object') parser.add_option('-b', '--bind', dest='address', help='The hostname:port the app should listen on.') parser.add_option('-d', '--debug', dest='use_debugger', action='store_true', default=False, help='Use Werkzeug\'s debugger.') parser.add_option('-r', '--reload', dest='use_reloader', action='store_true', default=False, help='Reload Python process if modules change.') options, args = parser.parse_args() hostname, port = None, None if options.address: address = options.address.split(':') hostname = address[0] if len(address) > 1: port = address[1] if len(args) != 1: sys.stdout.write('No application supplied, or too much. See --help\n') sys.exit(1) app = import_string(args[0]) run_simple( hostname=(hostname or '127.0.0.1'), port=int(port or 5000), application=app, use_reloader=options.use_reloader, use_debugger=options.use_debugger )
def iter_suites(): """Yields all testsuites.""" for module in find_modules(__name__): mod = import_string(module) if hasattr(mod, 'suite'): yield mod.suite()
def from_object(self, obj): """Updates the values from the given object. An object can be of one of the following two types: - a string: in this case the object with that name will be imported - an actual object reference: that object is used directly Objects are usually either modules or classes. Just the uppercase variables in that object are stored in the config. Example usage:: app.config.from_object('yourapplication.default_config') from yourapplication import default_config app.config.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. :param obj: an import name or object """ if isinstance(obj, string_types): obj = import_string(obj) for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key)
def get_format(obj): content_formats = get_content_formats() try: obj_content_format = content_formats[obj['content_format']] content_format = import_string( obj_content_format['content_format_class'] )() return content_format except (KeyError): return PlainFormat()
def from_object(self, obj): """Updates the values from the given object. An object can be of one of the following two types: - a string: in this case the object with that name will be imported - an actual object reference: that object is used directly Objects are usually either modules or classes. :meth:`from_object` loads only the uppercase attributes of the module/class. A ``dict`` object will not work with :meth:`from_object` because the keys of a ``dict`` are not attributes of the ``dict`` class. Example of module-based configuration:: app.config.from_object('yourapplication.default_config') from yourapplication import default_config app.config.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. See :ref:`config-dev-prod` for an example of class-based configuration using :meth:`from_object`. :param obj: an import name or object """ if isinstance(obj, string_types): obj = import_string(obj) for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key)
def obj_or_import_string(value, default=None): """Import string or return object. :params value: Import path or class object to instantiate. :params default: Default object to return if the import fails. :returns: The imported object. """ if isinstance(value, str): return import_string(value) elif value: return value return default
def main(): '''A simple command-line interface for :py:func:`run_simple`.''' # in contrast to argparse, this works at least under Python < 2.7 import optparse from werkzeug.utils import import_string parser = optparse.OptionParser(usage='Usage: %prog [options] app_module:app_object') parser.add_option('-b', '--bind', dest='address', help='The hostname:port the app should listen on.') parser.add_option('-d', '--debug', dest='use_debugger', action='store_true', default=False, help='Use Werkzeug\'s debugger.') parser.add_option('-r', '--reload', dest='use_reloader', action='store_true', default=False, help='Reload Python process if modules change.') options, args = parser.parse_args() hostname, port = None, None if options.address: address = options.address.split(':') hostname = address[0] if len(address) > 1: port = address[1] if len(args) != 1: sys.stdout.write('No application supplied, or too much. See --help\n') sys.exit(1) app = import_string(args[0]) run_simple( hostname=(hostname or '127.0.0.1'), port=int(port or 5000), application=app, use_reloader=options.use_reloader, use_debugger=options.use_debugger )
def update(settings=None, force=False): """Updates the settings via a fixture. All fixtures have to be placed in the `fixture`. Usage: python manage.py update -s your_fixture """ try: fixture = import_string( "flaskbb.fixtures.{}".format(settings) ) fixture = fixture.fixture except ImportError: raise "{} fixture is not available".format(settings) overwrite_group = overwrite_setting = False if force: overwrite_group = overwrite_setting = True count = update_settings_from_fixture( fixture=fixture, overwrite_group=overwrite_group, overwrite_setting=overwrite_setting ) print("{} groups and {} settings updated.".format( len(count.keys()), len(count.values())) )
def deposit_class(self): """Return a class implementing `publish` method.""" cls = current_app.config['GITHUB_DEPOSIT_CLASS'] if isinstance(cls, string_types): cls = import_string(cls) assert isinstance(cls, type) return cls
def release_api_class(self): """Github Release API class.""" cls = current_app.config['GITHUB_RELEASE_CLASS'] if isinstance(cls, string_types): cls = import_string(cls) assert issubclass(cls, GitHubRelease) return cls
def record_serializer(self): """Github Release API class.""" imp = current_app.config['GITHUB_RECORD_SERIALIZER'] if isinstance(imp, string_types): return import_string(imp) return imp