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)
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
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
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
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
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)
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))
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')
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))
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'))
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)
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)
def get_spec(self, name, package): spec = name isabs = os.path.isabs(name) if (not isabs) and (not ':' in name) and package: # relative asset spec if not isabs: pp = package_path(package) spec = os.path.join(pp, spec) spec = asset_spec_from_abspath(spec, package) return spec
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
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
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')
def test_destination_package(): """Testing translation package:path resolve.""" request = Mock() request.registry = { "localize": build_localize_config( {"localize.translation.destination": "tests:translations"}) } result = destination_path(request) assert result == os.path.join(package_path(sys.modules["tests"]), "translations")
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
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
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
def _translation_template_path(self, spec): # pylint:disable=no-self-use """ Calculate path to translation template file. :param str spec: either full path, or package related path """ # resolving possible asset spec to path (pyramid way): package_name, filename = resolve_asset_spec(spec) if package_name is None: # absolute filename return os.path.abspath(filename) __import__(package_name) package = sys.modules[package_name] return os.path.abspath(os.path.join(package_path(package), filename))
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)
def create_static_url(obj, mixin_name, spec=None, wrapper_class=None): if spec is None: spec = obj.asset_spec if type(mixin_name) is tuple: spec, mixin_name = mixin_name asset_spec = "{spec}/{name}".format(spec=spec, name=mixin_name) try: return static_url_cache[(asset_spec, wrapper_class)] except KeyError: pass if spec[0:12] != 'solute.epfl:' and spec[0:12] != 'solute.epfl.': static_url_cache[(asset_spec, wrapper_class)] = obj.request.static_path(asset_spec) if wrapper_class: static_url_cache[(asset_spec, wrapper_class)] = wrapper_class( static_url_cache[(asset_spec, wrapper_class)]) return static_url_cache[(asset_spec, wrapper_class)] static_path = obj.request.static_path(asset_spec) static_mixin = 'static/' if spec == 'solute.epfl:static': static_mixin = '' output = { 'base_path': path.package_path(solute.epfl), 'relative_path': static_path[5:len(static_path) - len(mixin_name)], 'mixin': static_mixin, 'mixin_name': mixin_name } absolute_path = "{base_path}{relative_path}{mixin}{mixin_name}".format( **output) if exists(absolute_path): static_url_cache[(asset_spec, wrapper_class)] = obj.request.static_path(asset_spec) if wrapper_class: static_url_cache[(asset_spec, wrapper_class)] = wrapper_class( static_url_cache[(asset_spec, wrapper_class)]) return static_url_cache[(asset_spec, wrapper_class)] elif spec != 'solute.epfl:static': static_url_cache[(asset_spec, wrapper_class)] = create_static_url( obj, mixin_name, 'solute.epfl:static') if wrapper_class: static_url_cache[(asset_spec, wrapper_class)] = wrapper_class( static_url_cache[(asset_spec, wrapper_class)]) return static_url_cache[(asset_spec, wrapper_class)] else: # return obj.request.static_path(asset_spec) raise Exception('Static dependency not found. %s' % asset_spec)
def _translation_template_path(self, spec): ''' calculates path to translation template file :param str spec: either full path, or package related path ''' # resolving possible asset spec to path (pyramid way): package_name, filename = resolve_asset_spec(spec) if package_name is None: # absolute filename return os.path.abspath(filename) else: __import__(package_name) package = sys.modules[package_name] return os.path.abspath(os.path.join(package_path(package), filename))
def prod_fullfile_app(): """Configure the Pyramid application. We need to be sure that we get full path to pass always, no matter where this test is being run. """ package_name, filename = resolve_asset_spec('tests:config') __import__(package_name) package = sys.modules[package_name] path = os.path.join(package_path(package), filename) # Configure redirect routes config = config_factory(**{'env': 'prod', 'yml.location': path}) # Add routes for change_password, change_username, app = TestApp(config.make_wsgi_app()) return App(app, config)
def destination_path(request): ''' Returns absolute path of the translation destination :param pyramid.request.Request request: a request object :returns: A combined translation destination path :rtype: str ''' package_name, filename = resolve_asset_spec(request.config.localize.translation.destination) 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) return directory
def setUp(self): testing.setUp() self.tempdir = None import sys import os import tempfile from pyramid.path import package_path from pyramid.tests import fixtureapp as package import shutil tempdir = tempfile.mkdtemp() modname = 'myfixture%s' % self.i self.i += 1 self.packagepath = os.path.join(tempdir, modname) fixturedir = package_path(package) shutil.copytree(fixturedir, self.packagepath) sys.path.insert(0, tempdir) self.module = __import__(modname) self.tempdir = tempdir
def destination_path(request): """ Return absolute path of the translation destination. :param pyramid.request.Request request: a request object :returns: A combined translation destination path :rtype: str """ package_name, filename = resolve_asset_spec( request.registry['config'].localize.translation.destination) 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) return directory
def _translate_config_path(location): """ Translate location into fullpath according asset specification. Might be package:path for package related paths, or simply path :param str location: resource location :returns: fullpath :rtype: str """ # getting spec path package_name, filename = resolve_asset_spec(location.strip()) if not package_name: path = filename else: package = __import__(package_name) path = os.path.join(package_path(package), filename) return path
def quick_serve(sql_session_factory=None, port=8080): """Start a HTTP server for your REST service. This function provides quick way to run a webserver for your REST service. The webserver will listen on port 8080 on all IP addresses of the local machine. If you need to configure the underlying Pyramid system, or you want to use a different HTTP server you will need to create the WSGI application yourself. Instead of using `quick_serve` you will need to do something like this: .. code-block:: python :linenos: from pyramid.config import Configurator from wsgiref.simple_server import make_server config = Configurator() config.include('rest_toolkit') config.scan() app = config.make_wsgi_app() make_server('0.0.0.0', 8080, app).serve_forever() :param sql_session_factory: A factory function to return a SQLAlchemy session. This is generally a :py:class:`scoped_session <sqlalchemy:sqlalchemy.orm.session.scoped_session>` instance, and commonly called ``Session`` or ``DBSession``. :param int port: TCP port to use for HTTP server. """ config = Configurator() config.include('rest_toolkit') if sql_session_factory is not None: config.include('rest_toolkit.ext.sql') config.set_sqlalchemy_session_factory(sql_session_factory) pkg = caller_package() config.add_static_view('static', package_path(pkg)) config.scan(pkg) app = config.make_wsgi_app() server = make_server('0.0.0.0', port, app) server.serve_forever()
def create_static_url(obj, mixin_name, spec=None, wrapper_class=None): if spec is None: spec = obj.asset_spec if type(mixin_name) is tuple: spec, mixin_name = mixin_name asset_spec = "{spec}/{name}".format(spec=spec, name=mixin_name) try: return static_url_cache[(asset_spec, wrapper_class)] except KeyError: pass if spec[0:12] != 'solute.epfl:' and spec[0:12] != 'solute.epfl.': static_url_cache[(asset_spec, wrapper_class)] = obj.request.static_path(asset_spec) if wrapper_class: static_url_cache[(asset_spec, wrapper_class)] = wrapper_class(static_url_cache[(asset_spec, wrapper_class)]) return static_url_cache[(asset_spec, wrapper_class)] static_path = obj.request.static_path(asset_spec) static_mixin = 'static/' if spec == 'solute.epfl:static': static_mixin = '' output = {'base_path': path.package_path(solute.epfl), 'relative_path': static_path[5:len(static_path) - len(mixin_name)], 'mixin': static_mixin, 'mixin_name': mixin_name} absolute_path = "{base_path}{relative_path}{mixin}{mixin_name}".format(**output) if exists(absolute_path): static_url_cache[(asset_spec, wrapper_class)] = obj.request.static_path(asset_spec) if wrapper_class: static_url_cache[(asset_spec, wrapper_class)] = wrapper_class(static_url_cache[(asset_spec, wrapper_class)]) return static_url_cache[(asset_spec, wrapper_class)] elif spec != 'solute.epfl:static': static_url_cache[(asset_spec, wrapper_class)] = create_static_url(obj, mixin_name, 'solute.epfl:static') if wrapper_class: static_url_cache[(asset_spec, wrapper_class)] = wrapper_class(static_url_cache[(asset_spec, wrapper_class)]) return static_url_cache[(asset_spec, wrapper_class)] else: # return obj.request.static_path(asset_spec) raise Exception('Static dependency not found. %s' % asset_spec)
def __call__(self, value, system): """Render the template.""" pkg, name = resolve_asset_spec(self.info.name) tpl = os.path.join(package_path(self.info.package), name) return pystache.render(open(tpl, 'r').read(), value)
def _callFUT(self, package): from pyramid.path import package_path return package_path(package)
"""Tests conftest file.""" import os import sys import pytest from pyramid.asset import resolve_asset_spec from pyramid.path import package_path from pytest_pyramid import factories package_name, filename = resolve_asset_spec('tests:config') __import__(package_name) package = sys.modules[package_name] full_path = os.path.join(package_path(package), filename) @pytest.fixture(scope='function', params=['tests:config', 'tests:config/config.yaml', full_path]) def base_config(request): """Basic config parametrized for different configuration location.""" return factories.pyramid_config({ 'yaml.location': request.param, 'pyramid.includes': ['tzf.pyramid_yml'] })(request) @pytest.fixture(scope='function', params=['tests:config', 'tests:config/config.yaml', full_path]) def prod_config(request): """Basic with env set parametrized for different configuration location.""" return factories.pyramid_config({