本文整理汇总了Python中pyramid.path.package_path函数的典型用法代码示例。如果您正苦于以下问题:Python package_path函数的具体用法?Python package_path怎么用?Python package_path使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了package_path函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: config_defaults
def config_defaults(configurator, config, files=['config.yml']):
'''
Reads and extends/creates configuration from yaml source.
.. note::
If exists, this method extends config with defaults, so it will not override existing values,
merely add those, that were not defined already!
:param pyramid.config.Configurator configurator: pyramid's app configurator
:param string config: yaml file locations
:param list files: list of files to include from location
'''
# getting spec path
package_name, filename = resolve_asset_spec(config)
if not package_name:
path = filename
else:
__import__(package_name)
package = sys.modules[package_name]
path = os.path.join(package_path(package), filename)
config = ConfigManager(files=[os.path.join(path, f) for f in files])
# we could use this method both for creating and extending. Hence the checks to not override
if not 'config' in configurator.registry:
configurator.registry['config'] = config
else:
config.merge(configurator.registry['config'])
configurator.registry['config'] = config
示例2: get_spec
def get_spec(self, name, package):
if not package:
# if there's no package, we can't do any conversion
return name
spec = name
isabspath = os.path.isabs(name)
colon_in_name = ":" in name
isabsspec = colon_in_name and (not isabspath)
isrelspec = (not isabsspec) and (not isabspath)
# if it's already an absolute spec, we don't need to do anything,
# but if it's a relative spec or an absolute path, we need to try
# to convert it to an absolute spec
if isrelspec:
# convert relative asset spec to absolute asset spec
pp = package_path(package)
spec = os.path.join(pp, spec)
spec = asset_spec_from_abspath(spec, package)
elif isabspath:
# convert absolute path to absolute asset spec
spec = asset_spec_from_abspath(spec, package)
return spec
示例3: __call__
def __call__(self, value, system):
package, filename = resolve_asset_spec(self.info.name)
template = os.path.join(package_path(self.info.package), filename)
template_fh = open(template)
template_stream = template_fh.read()
template_fh.close()
return pystache.render(template_stream, value)
示例4: __call__
def __call__(self, wrapped):
settings = self.__dict__.copy()
def callback(context, name, ob):
context.config.add_view(view=ob, **settings)
info = self.venusian.attach(wrapped, callback, category='bfg')
if info.scope == 'class':
# if the decorator was attached to a method in a class, or
# otherwise executed at class scope, we need to set an
# 'attr' into the settings if one isn't already in there
if settings['attr'] is None:
settings['attr'] = wrapped.__name__
# try to convert the renderer provided into a fully qualified
# resource specification
abspath = settings.get('renderer')
if abspath is not None and '.' in abspath:
isabs = os.path.isabs(abspath)
if not (':' in abspath and not isabs):
# not already a resource spec
if not isabs:
pp = package_path(info.module)
abspath = os.path.join(pp, abspath)
resource = resource_spec_from_abspath(abspath, info.module)
settings['renderer'] = resource
return wrapped
示例5: add_translation_dirs
def add_translation_dirs(self, *specs):
""" Add one or more :term:`translation directory` paths to the
current configuration state. The ``specs`` argument is a
sequence that may contain absolute directory paths
(e.g. ``/usr/share/locale``) or :term:`asset specification`
names naming a directory path (e.g. ``some.package:locale``)
or a combination of the two.
Example:
.. code-block:: python
config.add_translation_dirs('/usr/share/locale',
'some.package:locale')
Later calls to ``add_translation_dir`` insert directories into the
beginning of the list of translation directories created by earlier
calls. This means that the same translation found in a directory
added later in the configuration process will be found before one
added earlier in the configuration process. However, if multiple
specs are provided in a single call to ``add_translation_dirs``, the
directories will be inserted into the beginning of the directory list
in the order they're provided in the ``*specs`` list argument (items
earlier in the list trump ones later in the list).
"""
directories = []
introspectables = []
for spec in specs[::-1]: # reversed
package_name, filename = self._split_spec(spec)
if package_name is None: # absolute filename
directory = filename
else:
__import__(package_name)
package = sys.modules[package_name]
directory = os.path.join(package_path(package), filename)
if not os.path.isdir(os.path.realpath(directory)):
raise ConfigurationError('"%s" is not a directory' %
directory)
intr = self.introspectable('translation directories', directory,
spec, 'translation directory')
intr['directory'] = directory
intr['spec'] = spec
introspectables.append(intr)
directories.append(directory)
def register():
for directory in directories:
tdirs = self.registry.queryUtility(ITranslationDirectories)
if tdirs is None:
tdirs = []
self.registry.registerUtility(tdirs,
ITranslationDirectories)
tdirs.insert(0, directory)
self.action(None, register, introspectables=introspectables)
示例6: registerTemplateCustomizations
def registerTemplateCustomizations(config, _dir, package):
registry = config.registry
if TEMPLATE_CUSTOMIZATIONS not in registry:
registry[TEMPLATE_CUSTOMIZATIONS] = {}
path = os.path.join(package_path(package), _dir)
for fi in os.listdir(path):
registry[TEMPLATE_CUSTOMIZATIONS][fi] = (
package, os.path.join(_dir, fi))
示例7: test_destination_package
def test_destination_package():
"""Testing translation package:path resolve."""
request = Mock()
request.registry = {'config': Mock()}
mock_configuration = {'localize.translation.destination': 'tests:translations'}
request.registry['config'].configure_mock(**mock_configuration)
result = destination_path(request)
assert result == os.path.join(package_path(sys.modules['tests']), 'translations')
示例8: test_package
def test_package(self):
'''testing translation package:path resolve'''
request = Mock()
mock_configuration = {
'config.localize.translation.destination': 'tests:translations'}
request.configure_mock(**mock_configuration)
result = destination_path(request)
self.assertEqual(result,
os.path.join(package_path(sys.modules['tests']),
'translations'))
示例9: __call__
def __call__(self, value, system):
"""Render the template."""
pkg, name = resolve_asset_spec(self.info.name)
pkg_path = package_path(self.info.package)
tpl_path = os.path.join(pkg_path, name)
tpl_dir = os.path.split(tpl_path)[0]
renderer = pystache.Renderer(search_dirs=[tpl_dir, pkg_path])
return renderer.render_path(tpl_path, value)
示例10: add_translation_dirs
def add_translation_dirs(self, *specs):
""" Add one or more :term:`translation directory` paths to the
current configuration state. The ``specs`` argument is a
sequence that may contain absolute directory paths
(e.g. ``/usr/share/locale``) or :term:`asset specification`
names naming a directory path (e.g. ``some.package:locale``)
or a combination of the two.
Example:
.. code-block:: python
config.add_translation_dirs('/usr/share/locale',
'some.package:locale')
Later calls to ``add_translation_dir`` insert directories into the
beginning of the list of translation directories created by earlier
calls. This means that the same translation found in a directory
added later in the configuration process will be found before one
added earlier in the configuration process. However, if multiple
specs are provided in a single call to ``add_translation_dirs``, the
directories will be inserted into the beginning of the directory list
in the order they're provided in the ``*specs`` list argument (items
earlier in the list trump ones later in the list).
"""
for spec in specs[::-1]: # reversed
package_name, filename = self._split_spec(spec)
if package_name is None: # absolute filename
directory = filename
else:
__import__(package_name)
package = sys.modules[package_name]
directory = os.path.join(package_path(package), filename)
if not os.path.isdir(os.path.realpath(directory)):
raise ConfigurationError('"%s" is not a directory' % directory)
tdirs = self.registry.queryUtility(ITranslationDirectories)
if tdirs is None:
tdirs = []
self.registry.registerUtility(tdirs, ITranslationDirectories)
tdirs.insert(0, directory)
# XXX no action?
if specs:
# We actually only need an IChameleonTranslate function
# utility to be registered zero or one times. We register the
# same function once for each added translation directory,
# which does too much work, but has the same effect.
ctranslate = ChameleonTranslate(translator)
self.registry.registerUtility(ctranslate, IChameleonTranslate)
示例11: asset_spec_from_abspath
def asset_spec_from_abspath(abspath, package):
""" Try to convert an absolute path to a resource in a package to
a resource specification if possible; otherwise return the
absolute path. """
if getattr(package, "__name__", None) == "__main__":
return abspath
pp = package_path(package) + os.path.sep
if abspath.startswith(pp):
relpath = abspath[len(pp) :]
return "%s:%s" % (package_name(package), relpath.replace(os.path.sep, "/"))
return abspath
示例12: get_spec
def get_spec(self, name, package):
spec = name
isabs = os.path.isabs(name)
if (not isabs) and (not ':' in name) and package:
# relative resource spec
if not isabs:
pp = package_path(package)
spec = os.path.join(pp, spec)
spec = resource_spec_from_abspath(spec, package)
return spec
示例13: template_renderer_factory
def template_renderer_factory(info, impl, lock=registry_lock):
spec = info.name
reg = info.registry
package = info.package
isabs = os.path.isabs(spec)
if (not isabs) and (not ':' in spec) and package:
# relative resource spec
if not isabs:
pp = package_path(package)
spec = os.path.join(pp, spec)
spec = resource_spec_from_abspath(spec, package)
if os.path.isabs(spec):
# 'spec' is an absolute filename
if not os.path.exists(spec):
raise ValueError('Missing template file: %s' % spec)
renderer = reg.queryUtility(ITemplateRenderer, name=spec)
if renderer is None:
renderer = impl(spec)
# cache the template
try:
lock.acquire()
reg.registerUtility(renderer, ITemplateRenderer, name=spec)
finally:
lock.release()
else:
# spec is a package:relpath resource spec
renderer = reg.queryUtility(ITemplateRenderer, name=spec)
if renderer is None:
try:
package_name, filename = spec.split(':', 1)
except ValueError: # pragma: no cover
# somehow we were passed a relative pathname; this
# should die
package_name = caller_package(4).__name__
filename = spec
abspath = pkg_resources.resource_filename(package_name, filename)
if not pkg_resources.resource_exists(package_name, filename):
raise ValueError(
'Missing template resource: %s (%s)' % (spec, abspath))
renderer = impl(abspath)
settings = info.settings
if settings and not settings.get('reload_resources'):
# cache the template
try:
lock.acquire()
reg.registerUtility(renderer, ITemplateRenderer, name=spec)
finally:
lock.release()
return renderer
示例14: _asset_to_fixture
def _asset_to_fixture(asset: str) -> Path:
"""Translate :term:`asset` to absolute fixture path."""
package_name, file_name = resolve_asset_spec(asset)
if package_name:
package = __import__(package_name)
path = Path(package_path(package), file_name)
else:
path = Path(file_name)
if not path.is_dir():
msg = 'This is not a directory {}'.format(asset)
raise ConfigurationError(details=msg)
return path
示例15: __call__
def __call__(self, value, system):
"""
Call to renderer.
The renderer is cached for optimize access.
"""
registry = system['request'].registry
try:
xsl = registry.getUtility(IRenderer, system['renderer_name'])
except ComponentLookupError:
xsl = XslRenderer(os.path.join(package_path(self._info.package),
system['renderer_name']))
registry.registerUtility(xsl, IRenderer, system['renderer_name'])
return xsl(value, system)