本文整理汇总了Python中pyramid.path.AssetResolver.resolve方法的典型用法代码示例。如果您正苦于以下问题:Python AssetResolver.resolve方法的具体用法?Python AssetResolver.resolve怎么用?Python AssetResolver.resolve使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyramid.path.AssetResolver
的用法示例。
在下文中一共展示了AssetResolver.resolve方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: register_mustache_bundle
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
def register_mustache_bundle(cfg, name, path='', description=''):
""" Register mustache bundle;
:param name: module name
:param path: asset path
:param description:
"""
resolver = AssetResolver()
d = resolver.resolve(path).abspath()
if not os.path.isdir(d):
raise ConfigurationError("Directory is required: %s"%path)
discr = (ID_AMD_MODULE, name)
resolver = AssetResolver()
abs_path = resolver.resolve(path).abspath()
if not path or not os.path.isdir(abs_path):
raise ConfigurationError("Directory is required: %s"%path)
intr = Introspectable(ID_AMD_MODULE, discr, name, ID_AMD_MODULE)
intr['name'] = name
intr['path'] = path
intr['abs_path'] = abs_path
intr['description'] = description
storage = cfg.registry.setdefault(ID_BUNDLE, {})
storage[name] = intr
cfg.action(discr, introspectables=(intr,))
示例2: CloudMaker
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
class CloudMaker(object):
def __init__(self, context, request):
self.context = context
self.request = request
self.resolver = AssetResolver()
self.minsize = int(request.registry.settings.get('jcu.words.minsize', 10))
self.maxsize = int(request.registry.settings.get('jcu.words.maxsize', 100))
@view_config(name="keyword-cloud.png")
def keyword_cloud_png(self):
asset = self.resolver.resolve('jcuwords:keyword-cloud.png')
_cloud = open(asset.abspath()).read()
return Response(content_type='image/png',
body=_cloud)
@view_config(name="keyword-cloud")
def keyword_cloud(self):
return self.make_cloud(True)
@view_config(name="keyword-cloud-image")
def keyword_cloud_image(self):
image_url = self.request.resource_url(None, 'keyword-cloud.png')
return {'image': image_url}
def invalidate(self):
cache.region_invalidate(self.make_cloud, None, False)
cache.region_invalidate(self.make_cloud, None, True)
def make_cloud(self, output_html):
keywords = KeywordManager().all()
text = ' '.join([kw.keyword for kw in keywords])
if output_html:
max_tags = 30
max_size = 42
else:
max_tags = 100
max_size = self.maxsize
tags = make_tags(get_tag_counts(text)[:max_tags], minsize=self.minsize,
maxsize=max_size)
if output_html:
size = (900, 300)
result = create_html_data(tags, size=size,
layout=LAYOUT_HORIZONTAL)
else:
#now = datetime.utcnow()
#filename = 'jcuwords/static/clouds/keyword-cloud-%s.png' % now.isoformat()
cloud = self.resolver.resolve('jcuwords:keyword-cloud.png')
filename = cloud.abspath()
size = (1024, 500)
create_tag_image(tags, filename, size=size,
fontname='IM Fell DW Pica',
layout=LAYOUT_MIX)
image_url = self.request.resource_url(None, 'keyword-cloud.png')
result = {'image': image_url}
return result
示例3: extract_static_assets_from_components
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
def extract_static_assets_from_components(compo_list):
ar = AssetResolver()
js_paths = []
js_name = []
css_paths = []
css_name = []
# The Page needs to be in the webassets first, then all other pages, then all components.
for cls in compo_list:
for js in cls.js_name:
if type(js) is not tuple:
js = (cls.asset_spec, js)
if js in js_name:
continue
js_name.append(js)
js_paths.append(ar.resolve('/'.join(js)).abspath())
cls.js_name = cls.js_name + getattr(cls, 'js_name_no_bundle', [])
for css in cls.css_name:
if type(css) is not tuple:
css = (cls.asset_spec, css)
if css in css_name:
continue
css_name.append(css)
css_paths.append(ar.resolve('/'.join(css)).abspath())
cls.css_name = cls.css_name + getattr(cls, 'css_name_no_bundle', [])
return js_paths, js_name, css_paths, css_name
示例4: init_amd_spec
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
def init_amd_spec(config, cache_max_age=None):
cfg = ptah.get_settings(ptah.CFG_ID_PTAH, config.registry)
config.registry[ID_AMD_SPEC] = {}
if not cfg['amd-specs']:
return
if not cfg['amd-spec-dir']:
raise ConfigurationError("amd-spec-dir is required.")
resolver = AssetResolver()
directory = resolver.resolve(cfg['amd-spec-dir']).abspath()
specs = {}
for item in cfg['amd-specs']:
if ':' not in item:
spec = ''
specfile = item
else:
spec, specfile = item.split(':',1)
if spec in specs:
raise ConfigurationError("Spec '%s' already defined."%spec)
specs[spec] = specfile
spec_mods = {}
for spec, specfile in specs.items():
f = resolver.resolve(specfile).abspath()
parser = configparser.SafeConfigParser()
parser.read(f)
mods = {}
for section in parser.sections():
if section.endswith('.js'):
items = dict(parser.items(section))
url = items.get('url', '')
modules = items.get('modules', '')
modules = [s for s in [s.strip() for s in modules.split()]
if not s.startswith('#')]
if url:
item = {'url': url, 'name': section}
elif modules:
item = {'name': section,
'path': os.path.join(directory,section)}
mods[section] = item
for mod in modules:
mods[mod] = item
spec_mods[spec] = mods
config.registry[ID_AMD_SPEC] = spec_mods
config.registry[ID_AMD_SPEC_] = cache_max_age
示例5: PyramidResolver
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
class PyramidResolver(Resolver):
def __init__(self, env):
super(PyramidResolver, self).__init__(env)
self.resolver = AssetResolver(None)
def search_for_source(self, item):
try:
item = self.resolver.resolve(item).abspath()
except ImportError as e:
raise BundleError(e)
except ValueError as e:
return super(PyramidResolver, self).search_for_source(item)
# Take care of globs
if glob.has_magic(item):
return [
filename
for filename
in glob.iglob(item)
if not path.isdir(item)
]
else:
return item
def resolve_source_to_url(self, filepath, item):
request = get_current_request()
if ':' in item:
# webassets gives us an absolute path to the source file
# If the input item that generate this path was an asset spec
# try to resolve the package and recreate the asset spec to use
# for the static route generation.
package = item[:item.find(':')]
package_path = self.resolver.resolve('%s:' % package).abspath()
filepath = filepath.replace(package_path, '').strip('/')
spec = '%s:%s' % (package, filepath)
else:
spec = filepath
return request.static_url(spec)
def resolve_output_to_url(self, item):
if not path.isabs(item):
item = path.join(self.env.directory, item)
try:
request = get_current_request()
url = request.static_url(self.search_for_source(item))
return url
except ValueError as e:
if ':' in item:
e.message += '(%s)' % item
raise BundleError(e)
示例6: parse_asset_settings
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
def parse_asset_settings(settings):
config = configparser.SafeConfigParser()
asset_resolver = AssetResolver()
dotted_resolver = DottedNameResolver()
asset_config = settings.get('assets.config')
print asset_config
try:
s = asset_resolver.resolve(asset_config).abspath()
config.read(s)
except AttributeError:
raise
try:
store_locally = config.getboolean('assets', 'store_locally')
except configparser.NoSectionError:
try:
with open(asset_config) as fp:
config.readfp(fp)
except IOError:
raise
else:
store_locally = config.getboolean('assets', 'store_locally')
result = dict(
store_locally=store_locally,
tmp_path=asset_resolver.resolve(config.get('assets', 'tmp_path')).abspath(),
save_path=asset_resolver.resolve(config.get('assets', 'save_path')).abspath()
)
c = config.items('assets:local')
for key, value in c:
# Skip any urls since they don't need to be resolved
# TODO: Might produce bugs if module name starts with `http`
if value.startswith('http'):
result[key] = value
continue
try:
value = asset_resolver.resolve(value).abspath()
except ValueError:
# This gets raised if the name isn't in dotted notation
pass
except ImportError:
# This gets raised if there's ":" in the value but it's not a module
pass
finally:
result[key] = value
if not store_locally:
c = dict(config.items('assets:cloud'))
c['service'] = dotted_resolver.resolve(c.get('service'))
result.update(c)
return result
示例7: __init__
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
def __init__(self, pkg):
path = ptah.get_cfg_storage(MIGRATION_ID).get(pkg)
if path is None:
raise ValueError("Can't find package.")
res = AssetResolver(pkg)
self.dir = res.resolve('ptah:scripts').abspath()
self.versions = res.resolve(path).abspath()
if not os.access(self.versions, os.F_OK):
raise alembic.util.CommandError("Path doesn't exist: %r." % path)
示例8: test_api_ae_delete_correct
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
def test_api_ae_delete_correct(self):
a=AssetResolver()
self.request.params = MultiDict()
self.request.params.add('URI','testAppEnsemble')
response = AppEnsembleViews(self.context, self.request).api_action_ae_delete()
self.assertTrue(os.path.isfile(a.resolve(os.path.join('aof:tmp','ae-trash','testAppEnsemble.ae')).abspath()),"Error: App-Ensemble was not stored in the trash folder when delting")
self.assertEqual(response.status_code,200,'Error: AppEnsemble could not be deleted!')
aof.tests._create_test_AppEnsemble()
response = AppEnsembleViews(self.context, self.request).api_action_ae_delete()
aof.tests._create_test_AppEnsemble()
files=os.listdir(a.resolve(os.path.join('aof:tmp','ae-trash')).abspath())
self.assertGreaterEqual(len(fnmatch.filter(files,'testAppEnsemble*')),1,"Error: Renaming deleted AppEnsembles does not work!")
aof.tests._create_test_AppEnsemble()
示例9: register_less_bundle
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
def register_less_bundle(cfg, name, path, description='', watchdir=None):
""" Register less bundle;
:param name: module name
:param path: asset path
:param description:
"""
resolver = AssetResolver()
abs_path = resolver.resolve(path).abspath()
if not os.path.isfile(abs_path):
raise ConfigurationError("less file is required: %s" % path)
discr = (ID_BUNDLE, name)
intr = Introspectable(ID_BUNDLE, discr, name, ID_BUNDLE)
intr['name'] = name
intr['path'] = path
intr['abs_path'] = abs_path
intr['watchdir'] = watchdir or os.path.dirname(abs_path)
intr['description'] = description
storage = cfg.registry.setdefault(ID_BUNDLE, {})
storage[name] = intr
cfg.action(discr, introspectables=(intr,))
示例10: register
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
def register():
directories = []
resolver = AssetResolver(self.package_name)
# defer spec resolution until register to allow for asset
# overrides to take place in an earlier config phase
for spec in specs:
# the trailing slash helps match asset overrides for folders
if not spec.endswith('/'):
spec += '/'
asset = resolver.resolve(spec)
directory = asset.abspath()
if not asset.isdir():
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)
tdirs = self.registry.queryUtility(ITranslationDirectories)
if tdirs is None:
tdirs = []
self.registry.registerUtility(tdirs, ITranslationDirectories)
if override:
tdirs.extend(directories)
else:
for directory in reversed(directories):
tdirs.insert(0, directory)
示例11: main
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
def main(argv=sys.argv):
global settings
global resolver
if len(argv) < 2:
usage(argv)
sys.exit(1)
config_uri = argv[1]
setup_logging(config_uri)
settings = get_appsettings(config_uri)
resolver = AssetResolver('digital_ale')
dest_prefix = resolver.resolve(settings['scans.prefix']).abspath()
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
user = User.get_by_username(u'frank')
userid = user and user.id or None
#Base.metadata.create_all(engine)
with transaction.manager:
for filename in sys.argv[2:]:
if filename[-3:] == 'jpg':
import_jpg(filename, dest_prefix, userid)
elif filename[-3:] == 'txt':
import_txt(filename, userid)
else:
print >> sys.stderr, "Warning: (%s) Unknown filetype. Not importing. " % filename
示例12: __init__
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
def __init__(self, virtpath=None, abspath=None, type="file", mount_point=None):
""" mount_point: (virtual_path, absolute_path)
"""
self.mount_point = None
if mount_point:
ar = AssetResolver()
self.mount_point = (mount_point[0], ar.resolve(mount_point[1]).abspath())
if virtpath and abspath:
raise RuntimeError("ERR - need only virtpath nor abspath")
if virtpath:
self.virtpath = os.path.normpath(virtpath)
if mount_point is None:
self.mount_point = get_absmount(self.virtpath)
self.abspath = get_abspath(self.virtpath, self.mount_point)
elif abspath:
self.abspath = os.path.normpath(abspath)
if mount_point is None:
self.mount_point = get_virtmount(self.abspath)
self.virtpath = get_virtpath(self.abspath, self.mount_point)
else:
raise RuntimeERror("ERR - need either virtpath or abspath")
self.parent = None
self._meta = None
self.type = type
self.mimetype = None
示例13: add_bower_component
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
def add_bower_component(config, path, components_name=None):
"""
"""
registry = config.registry
resolver = AssetResolver()
directory = resolver.resolve(path).abspath()
if not os.path.isfile(os.path.join(directory, 'bower.json')):
raise ConfigurationError(
"Directory '{0}' does not contain 'bower.json' file"
.format(directory)
)
bower = get_bower(registry)
if components_name is None:
components_name = bower.components_name
discr = ('djed:static', directory, components_name)
def register():
info = BowerComponentInfo(directory, components_name)
registry.registerUtility(info, IBowerComponent, name='-'.join(discr))
config.action(discr, register)
示例14: view_file
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
def view_file(request):
form = get_form(AddSchema)
if request.POST:
if "simpan" in request.POST:
settings = get_settings()
input_file = request.POST["upload"].file
filename = request.POST["upload"].filename
ext = get_ext(filename)
if ext.lower() != ".png":
request.session.flash("File harus format png", "error")
return dict(form=form.render())
resolver = AssetResolver()
static_path = resolver.resolve("sipkd:static").abspath()
fullpath = os.path.join(static_path, "img/logo.png")
print "------------------>", fullpath
output_file = open(fullpath, "wb")
input_file.seek(0)
while True:
data = input_file.read(2 << 16)
if not data:
break
output_file.write(data)
return route_list(request)
return dict(form=form.render())
示例15: setUp
# 需要导入模块: from pyramid.path import AssetResolver [as 别名]
# 或者: from pyramid.path.AssetResolver import resolve [as 别名]
def setUp(self):
# Setting up Testpool and TestAppEnsemble
a = AssetResolver()
path = a.resolve(aof.tests.settings["app_pool_path"]).abspath()
ap = AppPool.Instance()
ap.load(source=path,format="turtle")
self.aeTests=AppEnsembleTests()
aof.tests._create_test_AppEnsemble()
#Set up Test-HTML for Documentation
aof.tests._create_test_html_file()
# Creating app with parameter
META=aof.tests.settings["META"]
app = main({},app_pool_path=aof.tests.settings["app_pool_path"],
app_ensemble_folder=aof.tests.settings["app_ensemble_folder"],
documentation_docs_path=aof.tests.settings["documentation_docs_path"],
META=META)
self.testapp = TestApp(app)
self.meta=ast.literal_eval(META)