def initialize(conf, env): """Initializes Jinja2 environment, prepares locale and configure some minor things. Filter and View are inited with conf and env, a request dict is returned. """ # initialize cache, optional to cache_dir cache.init(conf.get('cache_dir', None)) # set up templating environment env.engine = utils.import_object(conf['engine'])() env.engine.init(conf['layout_dir'], cache.cache_dir) env.engine.register('safeslug', helpers.safeslug) env.engine.register('tagify', lambda x: x) # try language set in LANG, if set correctly use it try: locale.setlocale(locale.LC_ALL, conf.get('lang', '')) except (locale.Error, TypeError): # try if LANG is an alias try: locale.setlocale(locale.LC_ALL, locale.locale_alias[conf['lang'].lower()]) except (locale.Error, KeyError): # LANG is not an alias, so we use system's default locale.setlocale(locale.LC_ALL, '') log.info('notice your OS does not support %s, fallback to %s', conf['lang'], locale.getlocale()[0]) if locale.getlocale()[0] is not None: conf['lang'] = locale.getlocale()[0][:2] else: # getlocale() is (None, None) aka 'C' conf['lang'] = 'en' if 'www_root' not in conf: log.warn('no `www_root` specified, using localhost:8000') conf['www_root'] = 'http://localhost:8000/' env['protocol'], env['netloc'], env['path'], x, y = urlsplit(conf['www_root']) # take off the trailing slash for www_root and path conf['www_root'] = conf['www_root'].rstrip('/') env['path'] = env['path'].rstrip('/') # check if encoding is available try: codecs.lookup(conf['encoding']) except LookupError: raise AcrylamidException('no such encoding available: %r' % conf['encoding']) # prepare, import and initialize filters and views if isinstance(conf['filters_dir'], basestring): conf['filters_dir'] = [conf['filters_dir'], ] if isinstance(conf['views_dir'], basestring): conf['views_dir'] = [conf['views_dir'], ] lazy.enable() filters.initialize(conf["filters_dir"], conf, env, exclude=conf["filters_ignore"], include=conf["filters_include"]) lazy.disable() # this has weird side effects with jinja2, so disabled after filters views.initialize(conf["views_dir"], conf, env) env['views'] = dict([(v.view, v) for v in views.get_views()]) entryfmt, pagefmt = '/:year/:slug/', '/:slug/' for view in views.get_views(): if view.view == 'entry': entryfmt = view.path if view.view == 'page': pagefmt = view.path conf['entry_permalink'] = conf['entry_permalink'] or entryfmt conf['page_permalink'] = conf['page_permalink'] or pagefmt return {'conf': conf, 'env': env}
def initialize(conf, env): """Initializes Jinja2 environment, prepares locale and configure some minor things. Filter and View are inited with conf and env, a data dict is returned. """ # initialize cache, optional to cache_dir cache.init(conf.get("cache_dir")) env["version"] = type("Version", (str,), dict(zip(["major", "minor"], LooseVersion(dist.version).version[:2])))( dist.version ) # crawl through CHANGES.md and stop on breaking changes if history.breaks(env, cache.emptyrun): cache.shutdown() print "Detected version upgrade that might break your configuration. Run" print "Acrylamid a second time to get rid of this message and premature exit." raise SystemExit # register hooks if env.options.parser.startswith(("co", "gen", "auto", "aco")): hooks.initialize(conf, env) # set up templating environment env.engine = import_object(conf["engine"])() env.engine.init(conf["theme"], cache.cache_dir) env.engine.register("safeslug", helpers.safeslug) env.engine.register("tagify", lambda x: x) # try language set in LANG, if set correctly use it try: locale.setlocale(locale.LC_ALL, str(conf.get("lang", ""))) except (locale.Error, TypeError): # try if LANG is an alias try: locale.setlocale(locale.LC_ALL, locale.locale_alias[str(conf.get("lang", "")).lower()]) except (locale.Error, KeyError): # LANG is not an alias, so we use system's default try: locale.setlocale(locale.LC_ALL, "") except locale.Error: pass # hope this makes Travis happy log.info("notice your OS does not support %s, fallback to %s", conf.get("lang", ""), locale.getlocale()[0]) if locale.getlocale()[0] is not None: conf["lang"] = locale.getlocale()[0][:2] else: # getlocale() is (None, None) aka 'C' conf["lang"] = "en" if "www_root" not in conf: log.warn("no `www_root` specified, using localhost:8000") conf["www_root"] = "http://localhost:8000/" # figure out timezone and set offset, more verbose for 2.6 compatibility td = datetime.now() - datetime.utcnow() offset = round(total_seconds(td) / 3600.0) conf["tzinfo"] = readers.Timezone(offset) # determine http(s), host and path env["protocol"], env["netloc"], env["path"], x, y = urlsplit(conf["www_root"]) # take off the trailing slash for www_root and path conf["www_root"] = conf["www_root"].rstrip("/") env["path"] = env["path"].rstrip("/") if env["path"]: conf["output_dir"] = conf["output_dir"] + env["path"] lazy.enable() filters.initialize(conf["filters_dir"][:], conf, env) lazy.disable() # this has weird side effects with jinja2, so disabled after filters views.initialize(conf["views_dir"][:], conf, env) env.views = views.Views(view for view in views.get_views()) entryfmt, pagefmt = "/:year/:slug/", "/:slug/" for view in views.get_views(): if view.name == "entry": entryfmt = view.path if view.name == "page": pagefmt = view.path conf.setdefault("entry_permalink", entryfmt) conf.setdefault("page_permalink", pagefmt) return {"conf": conf, "env": env}
from acrylamid import log, utils, core from acrylamid.filters import initialize, get_filters import attest tt = attest.Tests() log.init('foo', 35) conf = core.Configuration({'lang': 'en', 'theme': ''}) env = utils.Struct({ 'path': '', 'engine': None, 'options': type('X', (), {'ignore': False}) }) initialize([], conf, env) # now we have filters in path from acrylamid.filters.hyphenation import build class Entry(object): permalink = '/foo/' def __init__(self, lang='en'): self.lang = lang class Hyphenation(attest.TestBase): @attest.test
# -*- coding: utf-8 -*- import unittest from acrylamid import log, defaults, Environment from acrylamid.filters import initialize, get_filters log.init('foo', 35) conf = {'lang': 'en'} env = Environment({'path': '', 'options': type('X', (), {'ignore': False})}) initialize([], conf, env) # now we have filters in path from acrylamid.filters.hyphenation import build class Entry(object): permalink = '/foo/' def __init__(self, lang='en'): self.lang = lang class Hyphenation(unittest.TestCase): def test_hyphenate(self): hyph = get_filters()['Hyphenate'](conf, env, 'Hyphenate')
def initialize(conf, env): """Initializes Jinja2 environment, prepares locale and configure some minor things. Filter and View are inited with conf and env, a data dict is returned. """ # initialize cache, optional to cache_dir cache.init(conf.get('cache_dir')) env['version'] = type('Version', (str, ), dict(zip( ['major', 'minor'], LooseVersion(dist.version).version[:2])))(dist.version) # crawl through CHANGES.md and stop on breaking changes if history.breaks(env, cache.emptyrun): cache.shutdown() print("Detected version upgrade that might break your configuration. Run") print("Acrylamid a second time to get rid of this message and premature exit.") raise SystemExit # set up templating environment env.engine = import_object(conf['engine'])() env.engine.init(conf['theme'], cache.cache_dir) env.engine.register('safeslug', helpers.safeslug) env.engine.register('tagify', lambda x: x) # try language set in LANG, if set correctly use it try: locale.setlocale(locale.LC_ALL, str(conf.get('lang', ''))) except (locale.Error, TypeError): # try if LANG is an alias try: locale.setlocale(locale.LC_ALL, locale.locale_alias[str(conf.get('lang', '')).lower()]) except (locale.Error, KeyError): # LANG is not an alias, so we use system's default try: locale.setlocale(locale.LC_ALL, '') except locale.Error: pass # hope this makes Travis happy log.info('notice your OS does not support %s, fallback to %s', conf.get('lang', ''), locale.getlocale()[0]) if locale.getlocale()[0] is not None: conf['lang'] = locale.getlocale()[0][:2] else: # getlocale() is (None, None) aka 'C' conf['lang'] = 'en' if 'www_root' not in conf: log.warn('no `www_root` specified, using localhost:8000') conf['www_root'] = 'http://localhost:8000/' # figure out timezone and set offset, more verbose for 2.6 compatibility td = (datetime.now() - datetime.utcnow()) offset = round(total_seconds(td) / 3600.0) conf['tzinfo'] = readers.Timezone(offset) # determine http(s), host and path env['protocol'], env['netloc'], env['path'], x, y = urlsplit(conf['www_root']) # take off the trailing slash for www_root and path conf['www_root'] = conf['www_root'].rstrip('/') env['path'] = env['path'].rstrip('/') if env['path']: conf['output_dir'] = conf['output_dir'] + env['path'] lazy.enable() filters.initialize(conf["filters_dir"][:], conf, env) lazy.disable() # this has weird side effects with jinja2, so disabled after filters views.initialize(conf["views_dir"][:], conf, env) env.views = views.Views(view for view in views.get_views()) entryfmt, pagefmt = '/:year/:slug/', '/:slug/' for view in views.get_views(): if view.name == 'entry': entryfmt = view.path if view.name == 'page': pagefmt = view.path conf.setdefault('entry_permalink', entryfmt) conf.setdefault('page_permalink', pagefmt) # register webassets to theme engine, make webassets available as env.webassets assets.initialize(conf, env) return {'conf': conf, 'env': env}
def initialize(conf, env): """Initializes Jinja2 environment, prepares locale and configure some minor things. Filter and View are inited with conf and env, a request dict is returned. """ # initialize cache, optional to cache_dir cache.init(conf.get('cache_dir', None)) # set up templating environment env.engine = utils.import_object(conf['engine'])() env.engine.init(conf['layout_dir'], cache.cache_dir) env.engine.register('safeslug', helpers.safeslug) env.engine.register('tagify', lambda x: x) # try language set in LANG, if set correctly use it try: locale.setlocale(locale.LC_ALL, str(conf.get('lang', ''))) except (locale.Error, TypeError): # try if LANG is an alias try: locale.setlocale( locale.LC_ALL, locale.locale_alias[str(conf.get('lang', '')).lower()]) except (locale.Error, KeyError): # LANG is not an alias, so we use system's default try: locale.setlocale(locale.LC_ALL, '') except locale.Error: pass # hope this makes Travis happy log.info('notice your OS does not support %s, fallback to %s', conf.get('lang', ''), locale.getlocale()[0]) if locale.getlocale()[0] is not None: conf['lang'] = locale.getlocale()[0][:2] else: # getlocale() is (None, None) aka 'C' conf['lang'] = 'en' if 'www_root' not in conf: log.warn('no `www_root` specified, using localhost:8000') conf['www_root'] = 'http://localhost:8000/' # figure out timezone and set offset, more verbose for 2.6 compatibility td = (datetime.now() - datetime.utcnow()) total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 offset = round(total_seconds / 3600.0) conf['tzinfo'] = readers.Timezone(offset) # determine http(s), host and path env['protocol'], env['netloc'], env['path'], x, y = urlsplit( conf['www_root']) # take off the trailing slash for www_root and path conf['www_root'] = conf['www_root'].rstrip('/') env['path'] = env['path'].rstrip('/') # check if encoding is available try: codecs.lookup(conf['encoding']) except LookupError: raise AcrylamidException('no such encoding available: %r' % conf['encoding']) # prepare, import and initialize filters and views if isinstance(conf['filters_dir'], basestring): conf['filters_dir'] = [ conf['filters_dir'], ] if isinstance(conf['views_dir'], basestring): conf['views_dir'] = [ conf['views_dir'], ] lazy.enable() filters.initialize(conf["filters_dir"], conf, env, exclude=conf["filters_ignore"], include=conf["filters_include"]) lazy.disable( ) # this has weird side effects with jinja2, so disabled after filters views.initialize(conf["views_dir"], conf, env) env['views'] = dict([(v.view, v) for v in views.get_views()]) entryfmt, pagefmt = '/:year/:slug/', '/:slug/' for view in views.get_views(): if view.view == 'entry': entryfmt = view.path if view.view == 'page': pagefmt = view.path conf.setdefault('entry_permalink', entryfmt) conf.setdefault('page_permalink', pagefmt) return {'conf': conf, 'env': env}
def initialize(conf, env): """Initializes Jinja2 environment, prepares locale and configure some minor things. Filter and View are inited with conf and env, a request dict is returned. """ # initialize cache, optional to cache_dir cache.init(conf.get('cache_dir', None)) # rewrite static directory assets.initialize(conf, env) # set up templating environment env.engine = utils.import_object(conf['engine'])() env.engine.init(conf['theme'], cache.cache_dir) env.engine.register('safeslug', helpers.safeslug) env.engine.register('tagify', lambda x: x) # try language set in LANG, if set correctly use it try: locale.setlocale(locale.LC_ALL, str(conf.get('lang', ''))) except (locale.Error, TypeError): # try if LANG is an alias try: locale.setlocale(locale.LC_ALL, locale.locale_alias[str(conf.get('lang', '')).lower()]) except (locale.Error, KeyError): # LANG is not an alias, so we use system's default try: locale.setlocale(locale.LC_ALL, '') except locale.Error: pass # hope this makes Travis happy log.info('notice your OS does not support %s, fallback to %s', conf.get('lang', ''), locale.getlocale()[0]) if locale.getlocale()[0] is not None: conf['lang'] = locale.getlocale()[0][:2] else: # getlocale() is (None, None) aka 'C' conf['lang'] = 'en' if 'www_root' not in conf: log.warn('no `www_root` specified, using localhost:8000') conf['www_root'] = 'http://localhost:8000/' # figure out timezone and set offset, more verbose for 2.6 compatibility td = (datetime.now() - datetime.utcnow()) total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6 offset = round(total_seconds / 3600.0) conf['tzinfo'] = readers.Timezone(offset) # determine http(s), host and path env['protocol'], env['netloc'], env['path'], x, y = urlsplit(conf['www_root']) # take off the trailing slash for www_root and path conf['www_root'] = conf['www_root'].rstrip('/') env['path'] = env['path'].rstrip('/') # check if encoding is available try: codecs.lookup(conf['encoding']) except LookupError: raise AcrylamidException('no such encoding available: %r' % conf['encoding']) # prepare, import and initialize filters and views if isinstance(conf['filters_dir'], basestring): conf['filters_dir'] = [conf['filters_dir'], ] if isinstance(conf['views_dir'], basestring): conf['views_dir'] = [conf['views_dir'], ] lazy.enable() filters.initialize(conf["filters_dir"], conf, env) lazy.disable() # this has weird side effects with jinja2, so disabled after filters views.initialize(conf["views_dir"], conf, env) env.views = views.Views(view for view in views.get_views()) entryfmt, pagefmt = '/:year/:slug/', '/:slug/' for view in views.get_views(): if view.name == 'entry': entryfmt = view.path if view.name == 'page': pagefmt = view.path conf.setdefault('entry_permalink', entryfmt) conf.setdefault('page_permalink', pagefmt) return {'conf': conf, 'env': env}
def initialize(conf, env): """Initializes Jinja2 environment, prepares locale and configure some minor things. Filter and View are inited with conf and env, a request dict is returned. """ # initialize cache, optional to cache_dir cache.init(conf.get('cache_dir', None)) # set up templating environment env['jinja2'] = Environment(loader=ExtendedFileSystemLoader(conf['layout_dir']), bytecode_cache=FileSystemBytecodeCache(cache.cache_dir)) env['jinja2'].filters.update({'safeslug': helpers.safeslug, 'tagify': lambda x: x}) # try language set in LANG, if set correctly use it try: locale.setlocale(locale.LC_ALL, conf.get('lang', '')) except (locale.Error, TypeError): # try if LANG is an alias try: locale.setlocale(locale.LC_ALL, locale.locale_alias[conf['lang'].lower()]) except (locale.Error, KeyError): # LANG is not an alias, so we use system's default locale.setlocale(locale.LC_ALL, '') log.info('notice your OS does not support %s, fallback to %s', conf['lang'], locale.getlocale()[0]) if locale.getlocale()[0] is not None: conf['lang'] = locale.getlocale()[0][:2] else: # getlocale() is (None, None) aka 'C' conf['lang'] = 'en' if 'www_root' not in conf: log.warn('no `www_root` specified, using localhost:8000') conf['www_root'] = 'http://localhost:8000/' env['protocol'], env['netloc'], env['path'], x, y = urlsplit(conf['www_root']) # take off the trailing slash for www_root and path conf['www_root'] = conf['www_root'].rstrip('/') env['path'] = env['path'].rstrip('/') # check if encoding is available try: codecs.lookup(conf['encoding']) except LookupError: raise AcrylamidException('no such encoding available: %r' % conf['encoding']) # prepare, import and initialize filters and views if isinstance(conf['filters_dir'], basestring): conf['filters_dir'] = [conf['filters_dir'], ] if isinstance(conf['views_dir'], basestring): conf['views_dir'] = [conf['views_dir'], ] filters.initialize(conf["filters_dir"], conf, env, exclude=conf["filters_ignore"], include=conf["filters_include"]) views.initialize(conf["views_dir"], conf, env) env['views'] = dict([(v.view, v) for v in views.get_views()]) return {'conf': conf, 'env': env}
def initialize(conf, env): """Initializes Jinja2 environment, prepares locale and configure some minor things. Filter and View are inited with conf and env, a data dict is returned. """ # initialize cache, optional to cache_dir cache.init(conf.get('cache_dir')) env['version'] = type( 'Version', (str, ), dict(zip(['major', 'minor'], LooseVersion(dist.version).version[:2])))(dist.version) # crawl through CHANGES.md and stop on breaking changes if history.breaks(env, cache.emptyrun): cache.shutdown() print( "Detected version upgrade that might break your configuration. Run" ) print( "Acrylamid a second time to get rid of this message and premature exit." ) raise SystemExit # set up templating environment env.engine = import_object(conf['engine'])(conf['theme'], cache.cache_dir) env.engine.register('safeslug', helpers.safeslug) env.engine.register('tagify', lambda x: x) # try language set in LANG, if set correctly use it try: locale.setlocale(locale.LC_ALL, str(conf.get('lang', ''))) except (locale.Error, TypeError): # try if LANG is an alias try: locale.setlocale( locale.LC_ALL, locale.locale_alias[str(conf.get('lang', '')).lower()]) except (locale.Error, KeyError): # LANG is not an alias, so we use system's default try: locale.setlocale(locale.LC_ALL, '') except locale.Error: pass # hope this makes Travis happy log.info('notice your OS does not support %s, fallback to %s', conf.get('lang', ''), locale.getlocale()[0]) if locale.getlocale()[0] is not None: conf['lang'] = locale.getlocale()[0][:2] else: # getlocale() is (None, None) aka 'C' conf['lang'] = 'en' if 'www_root' not in conf: log.warn('no `www_root` specified, using localhost:8000') conf['www_root'] = 'http://localhost:8000/' # figure out timezone and set offset, more verbose for 2.6 compatibility td = (datetime.now() - datetime.utcnow()) offset = round(total_seconds(td) / 3600.0) conf['tzinfo'] = readers.Timezone(offset) # determine http(s), host and path env['protocol'], env['netloc'], env['path'], x, y = urlsplit( conf['www_root']) # take off the trailing slash for www_root and path conf['www_root'] = conf['www_root'].rstrip('/') env['path'] = env['path'].rstrip('/') if env['path']: conf['output_dir'] = conf['output_dir'] + env['path'] lazy.enable() filters.initialize(conf["filters_dir"][:], conf, env) lazy.disable( ) # this has weird side effects with jinja2, so disabled after filters views.initialize(conf["views_dir"][:], conf, env) env.views = views.Views(view for view in views.get_views()) entryfmt, pagefmt = '/:year/:slug/', '/:slug/' for view in views.get_views(): if view.name == 'entry': entryfmt = view.path if view.name == 'page': pagefmt = view.path conf.setdefault('entry_permalink', entryfmt) conf.setdefault('page_permalink', pagefmt) # register webassets to theme engine, make webassets available as env.webassets assets.initialize(conf, env) return {'conf': conf, 'env': env}
# -*- coding: utf-8 -*- import sys; reload(sys) sys.setdefaultencoding('utf-8') try: import unittest2 as unittest except ImportError: import unittest # NOQA from acrylamid import log, defaults, Environment from acrylamid.filters import initialize, get_filters log.init('foo', 35) initialize([], {'lang': 'en'}, Environment({'path': '', 'options': type('X', (), {'ignore': False})})) # now we have filters in path from acrylamid.filters.hyphenation import build class Entry(object): permalink = '/foo/' def __init__(self, lang='en'): self.lang = lang class TestHyphenation(unittest.TestCase):