本文整理汇总了Python中pyramid.path.AssetResolver类的典型用法代码示例。如果您正苦于以下问题:Python AssetResolver类的具体用法?Python AssetResolver怎么用?Python AssetResolver使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了AssetResolver类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: create_app
def create_app(settings):
from horus import groupfinder
from pyramid.config import Configurator
from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.path import AssetResolver
from pyramid.response import FileResponse
authn_policy = AuthTktAuthenticationPolicy(
settings['auth.secret'],
callback=groupfinder
)
authz_policy = ACLAuthorizationPolicy()
config = Configurator(
settings=settings,
authentication_policy=authn_policy,
authorization_policy=authz_policy,
root_factory='h.resources.RootFactory'
)
favicon = AssetResolver().resolve('h:favicon.ico')
config.add_route('favicon', '/favicon.ico')
config.add_view(
lambda request: FileResponse(favicon.abspath(), request=request),
route_name='favicon'
)
config.include(includeme)
return config.make_wsgi_app()
开发者ID:3divs,项目名称:h,代码行数:30,代码来源:__init__.py
示例2: __init__
def __init__(self, request):
super(NodeAppView, self).__init__(request)
view = request.view_name
subpath = request.subpath
if not len(subpath):
raise HTTPNotFound()
appname = subpath[0]
if len(subpath) == 1:
# check for existence
asset = 'haberdashery:apps/%s' % appname
resolver = AssetResolver()
descriptor = resolver.resolve(asset)
if not descriptor.exists():
raise HTTPNotFound()
# send back index to start load app
settings = self.get_app_settings()
basecolor = settings['default.css.basecolor']
template = 'trumpet:templates/webview-app.mako'
env = dict(appname=appname, basecolor=basecolor)
content = render(template, env)
self.response = Response(body=content)
else:
#asset = 'haberdashery:apps/%s' % appname
asset = os.path.join('haberdashery:apps', *subpath)
self.response = static_asset_response(request, asset)
开发者ID:umeboshi2,项目名称:trumpet.history,代码行数:25,代码来源:webview.py
示例3: view_file
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())
开发者ID:aagusti,项目名称:sipkd,代码行数:27,代码来源:upload.py
示例4: collect_static
def collect_static(self):
"""Collect all static files from all static views for the manifest."""
def recurse(collector, path):
for entry in scandir(path):
if entry.name.startswith("."):
# Dot files are usually backups or other no no files
continue
# Don't process our internal cache folder
if MARKER_FOLDER in entry.path:
continue
relative = os.path.relpath(entry.path, collector.root)
if entry.is_file():
collector.collect(path, name, entry, relative)
elif entry.is_dir():
recurse(collector, entry.path)
r = AssetResolver()
for name, asset_spec in self.views.items():
root = r.resolve(asset_spec).abspath()
collector = CopyAndHashCollector(root, self.settings)
recurse(collector, root)
results = collector.finish()
# Expose for testing
return results
开发者ID:LukeSwart,项目名称:websauna,代码行数:32,代码来源:static.py
示例5: register_less_bundle
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,))
开发者ID:calwi,项目名称:pyramid_amdjs,代码行数:26,代码来源:less.py
示例6: main
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
开发者ID:FrankNagel,项目名称:digital_ale,代码行数:27,代码来源:import_files.py
示例7: generate_webasset_bundles
def generate_webasset_bundles(config):
compo_bundles = extract_static_assets_from_components(epflutil.Discover.discovered_components)
page_bundles = []
pages = [epflpage.Page] + epflutil.Discover.discovered_pages
for cls in pages:
page_bundles.append(extract_static_assets_from_components([cls]))
if not asbool(config.registry.settings.get('epfl.webassets.active', False)):
return
ar = AssetResolver()
epfl_static = ar.resolve('solute.epfl:static')
my_env = Environment('%s/bundles' % epfl_static.abspath(), 'bundles')
for i, page in enumerate(pages):
js_paths, js_name, css_paths, css_name = page_bundles[i]
js_paths += compo_bundles[0]
js_name += compo_bundles[1]
css_paths += compo_bundles[2]
css_name += compo_bundles[3]
my_env.register('js%s' % i, Bundle(js_paths, filters='rjsmin', output='epfl.%(version)s.js'))
my_env.register('css%s' % i, Bundle(css_paths, output='epfl.%(version)s.css'))
page.js_name += [("solute.epfl:static", url) for url in my_env['js%s' % i].urls()]
page.css_name += [("solute.epfl:static", url) for url in my_env['css%s' % i].urls()]
page.bundled_names = js_name + css_name
开发者ID:JustusW,项目名称:pyramid_epfl,代码行数:32,代码来源:__init__.py
示例8: extract_static_assets_from_components
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
开发者ID:JustusW,项目名称:pyramid_epfl,代码行数:29,代码来源:__init__.py
示例9: register
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)
开发者ID:JDeuce,项目名称:pyramid,代码行数:31,代码来源:i18n.py
示例10: add_layer
def add_layer(cfg, layer, name='', path='', description=''):
""" add new layer
:param layer: layer id
:param name: name
:param path: asset path
:param description: module description
"""
if not path:
raise ConfigurationError('Path is required')
discr = (ID_LAYER, name, layer)
resolver = AssetResolver()
directory = resolver.resolve(path).abspath()
intr = Introspectable(ID_LAYER, discr, name, ID_LAYER)
intr['name'] = name
intr['layer'] = layer
intr['path'] = directory
intr['asset'] = path
intr['description'] = description
intr['filters'] = {}
storage = cfg.registry.setdefault(ID_LAYER, {})
layers = storage.setdefault(layer, [])
layers.insert(0, intr)
cfg.action(discr, introspectables=(intr,))
log.info("Add layer: %s path:%s"%(layer, path))
开发者ID:djedproject,项目名称:djed.renderer,代码行数:30,代码来源:layer.py
示例11: add_bower_component
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)
开发者ID:djedproject,项目名称:djed.static,代码行数:25,代码来源:__init__.py
示例12: __init__
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
开发者ID:trmznt,项目名称:rhombus,代码行数:25,代码来源:fsoverlay.py
示例13: setUp
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)
开发者ID:jo-tud,项目名称:aof,代码行数:27,代码来源:test_Views_functional.py
示例14: create_app
def create_app(settings):
from pyramid.config import Configurator
from pyramid.authorization import ACLAuthorizationPolicy
from pyramid.path import AssetResolver
from pyramid.response import FileResponse
from h.auth import HybridAuthenticationPolicy
from h.models import groupfinder
authn_policy = HybridAuthenticationPolicy(callback=groupfinder)
authz_policy = ACLAuthorizationPolicy()
config = Configurator(
settings=settings,
authentication_policy=authn_policy,
authorization_policy=authz_policy,
)
favicon = AssetResolver().resolve('h:favicon.ico')
config.add_route('favicon', '/favicon.ico')
config.add_view(
lambda request: FileResponse(favicon.abspath(), request=request),
route_name='favicon'
)
config.add_route('ok', '/ruok')
config.add_view(lambda request: 'imok', renderer='string', route_name='ok')
# Include all the pyramid subcomponents
config.include(includeme)
return config.make_wsgi_app()
开发者ID:jnishiyama,项目名称:h,代码行数:32,代码来源:__init__.py
示例15: get_template
def get_template(self, uri):
"""Fetch a template from the cache, or check the filesystem
for it
In addition to the basic filesystem lookup, this subclass will
use pkg_resource to load a file using the asset
specification syntax.
"""
isabs = os.path.isabs(uri)
if (not isabs) and (':' in uri):
# Windows can't cope with colons in filenames, so we replace the
# colon with a dollar sign in the filename mako uses to actually
# store the generated python code in the mako module_directory or
# in the temporary location of mako's modules
adjusted = uri.replace(':', '$')
try:
if self.filesystem_checks:
return self._check(adjusted, self._collection[adjusted])
else:
return self._collection[adjusted]
except KeyError:
asset = AssetResolver().resolve(uri)
if asset.exists():
srcfile = asset.abspath()
return self._load(srcfile, adjusted)
raise TopLevelLookupException(
"Can not locate template for uri %r" % uri)
try:
return TemplateLookup.get_template(self, uri)
except TemplateLookupException:
if isabs:
return self._load(uri, uri)
else:
raise
开发者ID:kr41,项目名称:pyramid_mako,代码行数:35,代码来源:__init__.py
示例16: _generate_md5
def _generate_md5(spec):
asset = AssetResolver(None).resolve(spec)
md5 = hashlib.md5()
with asset.stream() as stream:
for block in iter(lambda: stream.read(4096), b''):
md5.update(block)
return md5.hexdigest()
开发者ID:7924102,项目名称:pyramid,代码行数:7,代码来源:static.py
示例17: __call__
def __call__(self, info):
defname = None
asset, ext = info.name.rsplit('.', 1)
if '#' in asset:
asset, defname = asset.rsplit('#', 1)
spec = '%s.%s' % (asset, ext)
isabspath = os.path.isabs(spec)
colon_in_name = ':' in spec
isabsspec = colon_in_name and (not isabspath)
isrelspec = (not isabsspec) and (not isabspath)
try:
# try to find the template using default search paths
self.lookup.get_template(spec)
except TemplateLookupException:
if isrelspec:
# convert relative asset spec to absolute asset spec
resolver = AssetResolver(info.package)
asset = resolver.resolve(spec)
spec = asset.absspec()
else:
raise
return self.renderer_factory(spec, defname, self.lookup)
开发者ID:kr41,项目名称:pyramid_mako,代码行数:26,代码来源:__init__.py
示例18: normalize_path
def normalize_path(config, keyname):
try:
resolver = AssetResolver()
path = config.registry.settings[keyname]
return resolver.resolve(path).abspath()
except KeyError:
raise ConfigurationError("{} is not found in settings".format(keyname))
开发者ID:podhmo,项目名称:pyramid_separated,代码行数:7,代码来源:__init__.py
示例19: getabspath
def getabspath(fpath):
from pyramid.path import AssetResolver
a = AssetResolver('mypyramid')
resolver = a.resolve(fpath)
abspath = resolver.abspath()
logging.debug(abspath)
return abspath
开发者ID:Catentropy,项目名称:mylab,代码行数:7,代码来源:tools.py
示例20: CloudMaker
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
开发者ID:jcu-eresearch,项目名称:jcu.words,代码行数:60,代码来源:views.py
注:本文中的pyramid.path.AssetResolver类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论