本文整理汇总了Python中webassets.Environment.register方法的典型用法代码示例。如果您正苦于以下问题:Python Environment.register方法的具体用法?Python Environment.register怎么用?Python Environment.register使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类webassets.Environment
的用法示例。
在下文中一共展示了Environment.register方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _init_webassets
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
def _init_webassets(debug=False):
assets_env = Environment(directory=SITE_ASSET_DIR,
url=SITE_ASSET_URL_PREFIX,
cache=WEBASSETS_CACHE_DIR,
load_path=[SITE_ASSET_SRC_DIR])
assets_env.debug = debug
js = Bundle('js/*.js', filters='uglifyjs', output='js/app.js')
css = Bundle('sass/*.scss', filters='scss,cssmin', output='css/app.css')
assets_env.register('app_js', js)
assets_env.register('app_css', css)
cmd = CommandLineEnvironment(assets_env, log)
p = Process(target=lambda: cmd.watch())
def signal_handler(sig, frame):
try:
p.terminate()
except Exception:
pass
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
p.start()
return assets_env
示例2: compileJavascript
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
def compileJavascript():
environment = Environment('vendor/bootstrap/js/', 'javascript')
output = '../../../codemitts/resources/static/javascript/bootstrap.js'
bootstrap_javascript_bundle = Bundle('*', output=output)
environment.register('bootstrap_javascript_bundle',
bootstrap_javascript_bundle)
environment['bootstrap_javascript_bundle'].urls()
示例3: generate_webasset_bundles
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
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
示例4: setup
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
def setup(self):
# Setup the assets environment.
assets_env = AssetsEnvironment('', '')
self.foo_bundle = Bundle()
self.bar_bundle = Bundle()
assets_env.register('foo_bundle', self.foo_bundle)
assets_env.register('bar_bundle', self.bar_bundle)
# Inject a mock bundle class into the Jinja2 extension, so we
# can check on what exactly it does.
test_instance = self
class MockBundle(Bundle):
urls_to_fake = ['foo']
def __init__(self, *a, **kw):
Bundle.__init__(self, *a, **kw)
self.env = assets_env
# Kind of hacky, but gives us access to the last Bundle
# instance used by the extension.
test_instance.the_bundle = self
def urls(self, *a, **kw):
return self.urls_to_fake
self._old_bundle_class = AssetsExtension.BundleClass
AssetsExtension.BundleClass = self.BundleClass = MockBundle
# Setup the Jinja2 environment.
self.jinja_env = JinjaEnvironment()
self.jinja_env.add_extension(AssetsExtension)
self.jinja_env.assets_environment = assets_env
示例5: setupAssetEnviromentFromYAML
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
def setupAssetEnviromentFromYAML(app, yamlFile):
appDir = './' + app.config['APP_DIRECTORY'] + '/'
assetEnv = AssetsEnvironment(appDir, '/')
bundles = YAMLLoader(appDir + yamlFile).load_bundles()
for bundle in bundles:
assetEnv.register(bundle, bundles[bundle])
app.templateEnv.assets_environment = assetEnv
示例6: load_environment
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
def load_environment(self):
"""Load an ``Environment`` instance defined in the YAML file.
Expects the following format::
directory: ../static
url: /media
debug: True
updater: timestamp
config:
compass_bin: /opt/compass
another_custom_config_value: foo
bundles:
bundle-name:
filters: sass,cssutils
output: cache/default.css
contents:
- css/jquery.ui.calendar.css
- css/jquery.ui.slider.css
"""
f, filename = self._open()
try:
obj = self.yaml.load(f) or {}
# construct the environment
if not 'url' in obj or not 'directory' in obj:
raise LoaderError('"url" and "directory" must be defined')
directory = obj['directory']
if filename:
# If we know the location of the file, make sure that the
# paths included are considered relative to the file location.
directory = path.normpath(path.join(path.dirname(filename), directory))
env = Environment(directory, obj['url'])
# load environment settings
for setting in ('debug', 'cache', 'versions', 'url_expire',
'auto_build',
# TODO: The deprecated values; remove at some point
'expire', 'updater'):
if setting in obj:
setattr(env, setting, obj[setting])
# load custom config options
if 'config' in obj:
env.config.update(obj['config'])
# load bundles
bundles = self._get_bundles(obj.get('bundles', {}))
for name, bundle in bundles.iteritems():
env.register(name, bundle)
return env
finally:
f.close()
示例7: test_jinja2_config
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
def test_jinja2_config(self):
app_config = self.basic_valid_app_config.copy()
dict_loader = DictLoader({})
app_config.update({"jinja2": {"loader": dict_loader,
"use_webassets": True}})
webassets_env = Environment("/tmp", "/")
webassets_env.register("js", "dummy.js", "dummy2.js", output="dummy.js")
config = BlueberryPyConfiguration(app_config=app_config,
webassets_env=webassets_env)
self.assertEqual(config.jinja2_config, {"loader": dict_loader})
示例8: load_environment
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
def load_environment(self):
"""Load an ``Environment`` instance defined in the YAML file.
Expects the following format::
directory: ../static
url: /media
debug: True
updater: timestamp
config:
compass_bin: /opt/compass
another_custom_config_value: foo
bundles:
bundle-name:
filters: sass,cssutils
output: cache/default.css
contents:
- css/jquery.ui.calendar.css
- css/jquery.ui.slider.css
"""
f, filename = self._open()
try:
obj = self.yaml.load(f) or {}
env = Environment()
# Load environment settings
for setting in ('debug', 'cache', 'versions', 'url_expire',
'auto_build', 'url', 'directory',
# TODO: The deprecated values; remove at some point
'expire', 'updater'):
if setting in obj:
setattr(env, setting, obj[setting])
# Treat the 'directory' option special, make it relative to the
# path of the YAML file, if we know it.
if filename and 'directory' in env.config:
env.directory = path.normpath(
path.join(path.dirname(filename), env.directory))
# Load custom config options
if 'config' in obj:
env.config.update(obj['config'])
# Load bundles
bundles = self._get_bundles(obj.get('bundles', {}))
for name, bundle in bundles.iteritems():
env.register(name, bundle)
return env
finally:
f.close()
示例9: WPConfModifChat
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
class WPConfModifChat(WPConferenceModifBase):
def __init__(self, rh, conf):
WPConferenceModifBase.__init__(self, rh, conf)
self._conf = conf
self._tabs = {} # list of Indico's Tab objects
self._tabNames = rh._tabs
self._activeTabName = rh._activeTabName
self._aw = rh.getAW()
self._tabCtrl = wcomponents.TabControl()
plugin_htdocs = os.path.join(os.path.dirname(__file__), 'htdocs')
self._plugin_asset_env = Environment(plugin_htdocs, '/InstantMessaging')
self._plugin_asset_env.register('instant_messaging', Bundle('js/InstantMessaging.js',
filters='jsmin',
output="InstantMessaging_%(version)s.min.js"))
def getJSFiles(self):
return WPConferenceModifBase.getJSFiles(self) + \
self._plugin_asset_env['instant_messaging'].urls()
def getCSSFiles(self):
return WPConferenceModifBase.getCSSFiles(self) + \
['InstantMessaging/im.css']
def _createTabCtrl(self):
for tabName in self._tabNames:
url = urlHandlers.UHConfModifChat.getURL(self._conf, tab = tabName)
self._tabs[tabName] = self._tabCtrl.newTab(tabName, tabName, url)
self._setActiveTab()
def _setActiveSideMenuItem(self):
if self._pluginsDictMenuItem.has_key('Instant Messaging'):
self._pluginsDictMenuItem['Instant Messaging'].setActive(True)
def _setActiveTab(self):
self._tabs[self._activeTabName].setActive()
def _getTitle(self):
return WPConferenceModifBase._getTitle(self) + " - " + _("Chat management")
def _getPageContent(self, params):
if len(self._tabNames) > 0:
self._createTabCtrl()
wc = WConfModifChat.forModule(InstantMessaging, self._conf,
self._activeTabName, self._tabNames, self._aw)
return wcomponents.WTabControl(self._tabCtrl, self._getAW()).getHTML(wc.getHTML({}))
else:
return _("No available plugins, or no active plugins")
示例10: create_and_register_bundles
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
def create_and_register_bundles(section, filter, DEPLOY):
environment = Environment('.')
for option in config.options(section):
deps = [v.strip() for v in config.get(section, option).split(',')]
log.info("%s.%s has dependencies: %s", option, section, deps)
bndl = Bundle(*deps, filters=filter,
output=concat_string([DEPLOY, '/', option, '.', section]))
environment.register(option, bndl)
bndlgz = Bundle(*deps, filters=concat_string([filter, ', gzip']),
output=concat_string([DEPLOY, '/', option, '.', section, '.gz']))
environment.register(concat_string([option, 'gz']), bndlgz)
bndl.build()
bndlgz.build()
示例11: get_assets
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
def get_assets(options):
''' A helper to build the assets for the service
:param options: The options to initialize with
:returns: The initialized assets
'''
arguments = {
'directory': './static',
'url': options.asset_url,
'debug': options.debug,
'updater': 'timestamp',
'expire': 'querystring',
'cache': True,
}
environment = Environment(**arguments)
# ------------------------------------------------------------
# stylesheet bundle
# ------------------------------------------------------------
stylesheet = Bundle('css/*.css',
filters='cssutils', output='cache/speleo.css')
environment.register('stylesheet', stylesheet)
# ------------------------------------------------------------
# template bundle
# ------------------------------------------------------------
template = Bundle('tmpl/*.tmpl',
filters='jst', output='cache/speleo.jst.js', debug=False)
environment.config['jst_compiler'] = '_.template'
# ------------------------------------------------------------
# javascript bundle
# ------------------------------------------------------------
javascript = Bundle(
Bundle('js/lib/core/jquery.js', 'js/lib/core/underscore.js'),
template, # needs underscore
Bundle('js/lib/ace/ace.js', 'js/lib/ace/mode-javascript.js'),
Bundle('js/lib/*.js', 'js/speleo.js'),
filters='closure_js', output='cache/speleo.js')
environment.register('javascript', javascript)
# ------------------------------------------------------------
# output cache
# ------------------------------------------------------------
if not os.path.exists(os.path.join('./static', 'cache')):
os.mkdir(os.path.join('./static', 'cache'))
# ------------------------------------------------------------
# initialized
# ------------------------------------------------------------
return Assets(environment)
示例12: register_assets
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
def register_assets(settings):
"""
Initialize webassets environment and its bundles.
Arguments:
settings (conf.model.SettingsModel): Settings registry instance.
Returns:
webassets.Environment: New configured Webasset environment.
"""
logger = logging.getLogger('optimus')
if not settings.ENABLED_BUNDLES:
logger.warning(("Asset registering skipped as there are no enabled "
"bundle"))
return None
logger.info("Starting asset registering")
# Assets bundles
AVAILABLE_BUNDLES = getattr(settings, 'BUNDLES', {})
# Initialize webassets environment
assets_env = AssetsEnvironment()
assets_env.debug = settings.DEBUG
assets_env.url = settings.STATIC_URL
assets_env.directory = settings.STATIC_DIR
assets_env.load_path = [settings.SOURCES_DIR]
assets_env.cache = settings.WEBASSETS_CACHE
assets_env.url_expire = settings.WEBASSETS_URLEXPIRE
#
assets_env.optimus_registry = AssetRegistry()
# Register enabled assets bundles
for bundle_name in settings.ENABLED_BUNDLES:
logger.debug("Registering bundle: {}".format(bundle_name))
assets_env.register(bundle_name, AVAILABLE_BUNDLES[bundle_name])
assets_env.optimus_registry.add_bundle(bundle_name,
AVAILABLE_BUNDLES[bundle_name])
# When after bundle has been registered we can resolve it
for bundle_name in settings.ENABLED_BUNDLES:
logger.info(" Processing: {}".format(
assets_env[bundle_name].resolve_output()
))
# Avoid to loop on every bundle part if we are not in debug logger
if logger.getEffectiveLevel() == logging.DEBUG:
for url in assets_env[bundle_name].urls():
logger.debug(" - {}".format(url))
return assets_env
示例13: main
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
def main():
log = logging.getLogger('webassets')
log.addHandler(logging.StreamHandler())
log.setLevel(logging.DEBUG)
call(["coffee", "-c", "src/tambur.coffee"])
call(["coffee", "-c", "src/tambur_publisher.coffee"])
env = Environment('.', '/static')
tamburjs = Bundle(
'deps/sockjs-0.3.js',
'src/tambur.js', output='out/tambur.js')
tamburminjs = Bundle(
'deps/sockjs-0.3.js',
'src/tambur.js', filters='yui_js', output='out/tambur.min.js')
publishjs = Bundle(
'deps/sha1.js',
'deps/oauth.js',
'src/tambur_publisher.js', output='out/tambur_pub.js')
publishminjs = Bundle(
'deps/sha1.js',
'deps/oauth.js',
'src/tambur_publisher.js', filters='yui_js', output='out/tambur_pub.min.js')
env.register('tambur.js', tamburjs)
env.register('tambur.min.js', tamburminjs)
env.register('tambur_pub.js', publishjs)
env.register('tambur_pub.min.js', publishminjs)
cmdenv = CommandLineEnvironment(env, log)
cmdenv.build()
示例14: register_assets
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
def register_assets():
"""
Initialize webassets environment and its bundles
NOTE: The asset bundles building is lazy, webassets only do building when he is
invoked by his template tag **assets** and if it detect that a file in a
bundle has changed.
"""
logger = logging.getLogger('optimus')
if not settings.ENABLED_BUNDLES:
logger.warning("Asset registering skipped as there are no enabled bundles")
return None
logger.info("Starting asset registering")
# Assets bundles
AVAILABLE_BUNDLES = copy.deepcopy(COMMON_BUNDLES)
AVAILABLE_BUNDLES.update(getattr(settings, 'EXTRA_BUNDLES', {}))
# Initialize webassets environment
assets_env = AssetsEnvironment()
assets_env.debug = settings.DEBUG
assets_env.url = settings.STATIC_URL
assets_env.directory = settings.STATIC_DIR
assets_env.load_path = [settings.SOURCES_DIR]
assets_env.cache = settings.WEBASSETS_CACHE
#
assets_env.optimus_registry = AssetRegistry()
# Register enabled assets bundles
for bundle_name in settings.ENABLED_BUNDLES:
logger.debug("Registering bundle: %s", bundle_name)
# Little trick because Bundle does not know their used name in the webassets
# environment
AVAILABLE_BUNDLES[bundle_name]._internal_env_name = bundle_name
assets_env.register(bundle_name, AVAILABLE_BUNDLES[bundle_name])
assets_env.optimus_registry.add_bundle(AVAILABLE_BUNDLES[bundle_name])
# for debugging purpopse
for bundle_name in settings.ENABLED_BUNDLES:
logger.info(" Processing: %s", assets_env[bundle_name].resolve_output())
# TODO: conditionnal on the log level to avoid to loop on multiple items if not
# in a debug log level
for url in assets_env[bundle_name].urls():
logger.debug(" - %s", url)
return assets_env
示例15: load_environment
# 需要导入模块: from webassets import Environment [as 别名]
# 或者: from webassets.Environment import register [as 别名]
def load_environment(self):
"""Load an ``Environment`` instance defined in the YAML file.
Expects the following format::
directory: ../static
url: /media
debug: True
updater: timestamp
bundles:
bundle-name:
filters: sass,cssutils
output: cache/default.css
contents:
- css/jquery.ui.calendar.css
- css/jquery.ui.slider.css
"""
f, filename = self._open()
try:
obj = self.yaml.load(f) or {}
# construct the environment
if not "url" in obj or not "directory" in obj:
raise LoaderError('"url" and "directory" must be defined')
directory = obj["directory"]
if filename:
# If we know the location of the file, make sure that the
# paths included are considered relative to the file location.
directory = path.normpath(path.join(path.dirname(filename), directory))
env = Environment(directory, obj["url"])
# load environment settings
for setting in ("debug", "cache", "updater", "expire"):
if setting in obj:
setattr(env, setting, obj[setting])
# load bundles
bundles = self._get_bundles(obj.get("bundles", {}))
for name, bundle in bundles.iteritems():
env.register(name, bundle)
return env
finally:
f.close()