本文整理汇总了Python中pyramid.path.AssetResolver类的典型用法代码示例。如果您正苦于以下问题:Python AssetResolver类的具体用法?Python AssetResolver怎么用?Python AssetResolver使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了AssetResolver类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
示例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)
示例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())
示例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
示例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,))
示例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
示例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
示例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
示例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)
示例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))
示例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)
示例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
示例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)
示例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()
示例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