def get_environnement(self, assets_env=None): """ Init the Jinja environment """ exts = [] self.logger.debug( "No Jinja2 environment given, initializing a new environment") # It the assets environment is given, active the Jinja extension to use webassets if self.assets_env is not None: exts.append(AssetsExtension) # Enabled Jinja extensions for ext in settings.JINJA_EXTENSIONS: exts.append(ext) # Active i18n behaviors if i18n extension is loaded and Babel has been imported if 'jinja2.ext.i18n' in exts and support is not None: self.internationalized = True self.logger.debug("'i18n' enabled") # Boot Jinja environment env = Jinja2Environment(loader=FileSystemLoader( settings.TEMPLATES_DIR), extensions=exts) if assets_env: env.assets_environment = assets_env return env
def project_template_filter(blueberrypy_config, path): if path.endswith(".html_tmpl"): return Jinja2Environment(block_start_string="<%", block_end_string="%>", variable_start_string="<<", variable_end_string=">>", comment_start_string="<#", comment_end_string="#>") if path.endswith("_tmpl"): path = path[:-5] if path.endswith("rest_controller.py"): return blueberrypy_config.get("use_rest_controller") if path.endswith("controller.py") or path.find("static") != -1: return blueberrypy_config.get("use_controller") if path.find("/templates") != -1: return blueberrypy_config.get("use_controller") and \ blueberrypy_config.get("use_jinja2") if path.endswith("bundles.yml"): return blueberrypy_config.get("use_webassets") if path.endswith(".hidden"): return False if path.endswith("model.py") or path.endswith("api.py"): return blueberrypy_config.get("use_sqlalchemy") return True
def get_jinja_renderer(template_path): """ This returns a method render(template, data) that will render the provided template with the given data using an initialized jinja2 environment. The primary reasons why we need this are: - asset handling (for example for logos) - reloading of templates (while designing the template) :param template_path: the directory that contains all templates and assets """ # template_path asset_path = os.path.join(template_path, "assets") if not os.path.isdir(template_path): raise ValueError("%s must be a directory" % template_path) if not os.path.isdir(asset_path): raise ValueError("%s must be a directory" % asset_path) assets_env = AssetsEnvironment(asset_path, "file://" + os.path.abspath(asset_path)) jinja2_env = Jinja2Environment( extensions=[AssetsExtension], loader=FileSystemLoader(template_path), auto_reload=True, autoescape=True, # undefined=StrictUndefined ) jinja2_env.assets_environment = assets_env def jinja_env_renderer(template_filename, data): template = jinja2_env.get_template(template_filename) return template.render(data) return jinja_env_renderer
def configure_jinja2(assets_env=None, **kwargs): global jinja2_env autoescape = kwargs.pop("autoescape", False) extensions = kwargs.pop("extensions", []) global_functions = kwargs.pop("globals", None) if assets_env: from webassets.ext.jinja2 import AssetsExtension extensions.append(AssetsExtension) if autoescape: autoescape = lambda filename: filename.rsplit( '.', 1)[1] in ('html', 'xml', 'htm') if isinstance( filename, basestring) else False extensions.append("jinja2.ext.autoescape") jinja2_env = Jinja2Environment(autoescape=autoescape, extensions=extensions, **kwargs) if assets_env: jinja2_env.assets_environment = assets_env if global_functions: jinja2_env.globals.update(global_functions) return jinja2_env
def compile_pages_and_assets(dev=False): compiledSass = '' sass_files_to_compile = ['main.scss'] for sassFile in sass_files_to_compile: # with open('resources/css/scss/'+sassFile, 'r') as thisfile: # SassData=thisfile.read() compiledSass += sass.compile(filename='resources/css/scss/'+sassFile, include_paths='resources/css/scss/vendor/') with open('resources/css/sass.css', 'w') as outputFile: outputFile.write(compiledSass) if(dev): all_js = Bundle('**/*.js', filters='noop', output='packed.js') all_css = Bundle('**/*.css', filters='noop', output="main.css") else: all_js = Bundle('**/*.js', filters='jsmin', output='packed.js') all_css = Bundle('**/*.css', filters='cssmin', output="main.css") jinja_env = Jinja2Environment(extensions=[AssetsExtension]) jinja_env.loader = FileSystemLoader('.') assets_env = AssetsEnvironment(url='/assets', directory='resources') assets_env.register('all_js', all_js) assets_env.register('all_css', all_css) jinja_env.assets_environment = assets_env pages = [] pages_dir = 'pages' for path, subdirs, files in os.walk(pages_dir): for name in files: pages.append(os.path.join(path, name)[6:]) # print(pages) for page in pages: thisTemplate = jinja_env.get_template('pages/' + page) thisTempRendered = thisTemplate.render() file_name = 'output/' + page body_content_location = 'output/content/' + page pathlib.Path(os.path.dirname(file_name)).mkdir(parents=True, exist_ok=True) pathlib.Path(os.path.dirname(body_content_location)).mkdir(parents=True, exist_ok=True) with open(file_name, 'w') as tempFile: tempFile.write(thisTempRendered) # This bit is used for my ajax shenanigans # anything you want on a page needs to go on body though... result = re.search('<body>(.*)<\/body>', '"' + thisTempRendered.replace('"', '\"').replace('\n',' ') + '"') # print(result) onlyTheBodyPart = result.group(1) with open(body_content_location, 'w') as tempFile: tempFile.write(onlyTheBodyPart) src = 'resources' dst = 'output/assets' filelist = [] files = ['main.css', 'packed.js'] for filename in files: filelist.append(filename) fullpath = src + '/' + filename shutil.move(os.path.join(src, filename), os.path.join(dst, filename))
def __init__(self): tornado.web.Application.__init__(self, urls, **settings) self.assets_env = AssetsEnvironment('../static', '') self.env = Jinja2Environment(loader=FileSystemLoader( settings.get('template_path')), extensions=[AssetsExtension]) self.env.assets_environment = self.assets_env
def test_introspect_inclusion(temp_builds_dir): """ Template introspection to cover includes """ basepath = temp_builds_dir.join("views_base_introspect_inclusion") # Create directory structure templates_dir = os.path.join(basepath.strpath, "templates") os.makedirs(templates_dir) # Create dummy templates skeleton_template = os.path.join(templates_dir, "skeleton.html") sample_template = os.path.join(templates_dir, "sample.html") include_template = os.path.join(templates_dir, "inclusion.html") with open(skeleton_template, "w") as fp: fp.write(("""<html><body>""" """{% block content %}Nope{% endblock %}""" """</body></html>""")) with open(sample_template, "w") as fp: fp.write(( """{% extends "skeleton.html" %}""" """{% block content %}Hello World! {% include 'inclusion.html' %}""" """{% endblock %}""")) with open(include_template, "w") as fp: fp.write(("""I'm an inclusion""")) # Dummy settings settings = DummySettings() # Init Jinja environment jinja_env = Jinja2Environment(loader=FileSystemLoader(templates_dir), ) # Make a view to render view = PageViewBase( title="Dummy", destination="{language_code}/sample.html", template_name="sample.html", lang="fr", settings=settings, ) assert view._recurse_template_search(jinja_env, "sample.html") == [ "skeleton.html", "inclusion.html", ] assert view.introspect(jinja_env) == [ "sample.html", "skeleton.html", "inclusion.html", ]
def get_environnement(self, assets_env=None): """ Init and configure Jinja environment. Automatically enable some extensions and link possible asset environment. Keyword Arguments: assets_env (webassets.Environment): Webasset environment. Default is ``None``. If empty, webassets will not be available from page templates. Returns: jinja2.Jinja2Environment: Configured Jinja2 environment. """ exts = [] self.logger.debug( ("No Jinja2 environment given, initializing a " "new environment") ) # It the assets environment is given, active the Jinja extension to # use webassets if self.assets_env is not None: exts.append(AssetsExtension) # Enabled Jinja extensions for ext in self.settings.JINJA_EXTENSIONS: exts.append(ext) # Active i18n behaviors if i18n extension is loaded and Babel has been # imported if "jinja2.ext.i18n" in exts and babel_support is not None: self.internationalized = True self.logger.debug("'i18n' enabled") # Boot Jinja environment env = Jinja2Environment( loader=FileSystemLoader(self.settings.TEMPLATES_DIR), extensions=exts ) # Enable Jinja filters for name, module in self.settings.JINJA_FILTERS.items(): env.filters[name] = module if assets_env: env.assets_environment = assets_env return env
def __init__(self, settings): handlers = routes.get_routes() + [ tornado.web.URLSpec( r'/login/google', GoogleLoginHandler, name='login_google'), tornado.web.URLSpec(r'/', MainHandler, name='home'), tornado.web.URLSpec(r'/(.*)', tornado.web.StaticFileHandler, {'path': os.path.join(PRJ_ROOT, 'static')}, name='homestatic'), tornado.web.URLSpec(r'/login/', LoginHandler, name='login'), tornado.web.URLSpec(r'/login/facebook', FacebookLoginHandler, name='login_facebook'), tornado.web.URLSpec( r'/login/twitter', TwitterLoginHandler, name='login_twitter'), tornado.web.URLSpec(r'/logout', AuthLogoutHandler, name='logout'), #(r'/static/(.*)', tornado.web.StaticFileHandler, # {'path': os.path.join(PRJ_ROOT, 'static')}), ] if not settings['db_uri'].startswith('mongodb://'): settings['db_connection'] = connect(settings['db_uri']) else: #_tmp_db = settings['db_uri'][10:] #_tmp_db_name = _tmp_db.split('/')[1] #host="localhost", port=27017 #settings['db_connection'] = connect(_tmp_db_name, host="localhost", port=27017) pass template_dirs = [] jinja2_env = None if settings.get('template_path'): template_dirs.append(settings['template_path']) assets_env = AssetsEnvironment(settings['static_path'], '/') settings['jinja2_env'] = Jinja2Environment( loader=FileSystemLoader(template_dirs), extensions=[AssetsExtension]) settings['jinja2_env'].assets_environment = assets_env tornado.web.Application.__init__(self, handlers, **settings)
def test_custom_jinja(minimal_basic_settings, fixtures_settings, caplog): """ Init with settings from 'minimal_basic' structure and custom jinja environment """ # Get basic sample settings projectdir = os.path.join(fixtures_settings.fixtures_path, "minimal_basic") settings = minimal_basic_settings(projectdir) # Init a custom Jinja environment without any extension jinja_env = Jinja2Environment(loader=FileSystemLoader( settings.TEMPLATES_DIR), ) # Init builder with custom Jinja environment builder = PageBuilder(settings, jinja_env=jinja_env) # No enabled extension assert list(builder.jinja_env.extensions.keys()) == [] assert caplog.record_tuples == [ ("optimus", logging.DEBUG, ("PageBuilder initialized")), ]
def test_render(temp_builds_dir): """ Render a basic page """ basepath = temp_builds_dir.join("views_base_render") # Create directory structure templates_dir = os.path.join(basepath.strpath, "templates") os.makedirs(templates_dir) # Create dummy templates skeleton_template = os.path.join(templates_dir, "skeleton.html") sample_template = os.path.join(templates_dir, "sample.html") with open(skeleton_template, "w") as fp: fp.write(("""<html><body>""" """{% block content %}Nope{% endblock %}""" """</body></html>""")) with open(sample_template, "w") as fp: fp.write(("""{% extends "skeleton.html" %}""" """{% block content %}Hello World!{% endblock %}""")) # Make a view to render settings = DummySettings() view = PageViewBase( title="Dummy", destination="{language_code}/sample.html", template_name="sample.html", lang="fr", settings=settings, ) # Init Jinja environment jinja_env = Jinja2Environment(loader=FileSystemLoader(templates_dir), ) assert view.render(jinja_env) == "<html><body>Hello World!</body></html>"
def main(manifest, roms, bios, run_dry): """ Parse a manifest XML file and build readme files for rom systems and bios "lutro": { "download_links": [ "https://github.com/libretro/lutro-platformer", "https://github.com/libretro/lutro-game-of-life", "https://github.com/libretro/lutro-snake", "https://github.com/libretro/lutro-tetris", "https://github.com/libretro/lutro-iyfct", "https://github.com/libretro/lutro-pong" ], "extensions": [ "lua" ], "extra_comments": [ "Hello World!", "Lorem ipsum salace" ], "name": "LUA games", "bios": [] } "fds": { "download_links": [ "http://www.planetemu.net/roms/nintendo-famicom-disk-system" ], "extensions": [ "fds" ], "name": "Nintendo Family Computer Disk System", "bios": [ [ "ca30b50f880eb660a320674ed365ef7a", "disksys.rom" ] ] }, """ if run_dry: click.echo('* Run dry enabled, no file/directory will be created') click.echo('* Parse manifest from: {}'.format(manifest.name)) Manifest = ManifestParser(manifest).read() click.echo('* Jinja init with template dir on: {}'.format(TEMPLATES_DIR)) template_env = Jinja2Environment(loader=FileSystemLoader(TEMPLATES_DIR)) # Build roms readme files if roms: BIOS_DIST_FILEPATH = os.path.join(BIOS_DIST_PATH, ROMSYSTEM_README_FILENAME) romsystem_template = template_env.get_template( ROMSYSTEM_README_TEMPLATE) click.echo( '* Start building rom systems readme files to: {}'.format(roms)) for system_key, system_datas in Manifest.items(): click.echo(' - System : {}'.format(system_key)) system_path = os.path.join(roms, system_key) readme_path = os.path.join(system_path, ROMSYSTEM_README_FILENAME) # Fill template context with system datas context = { 'key': system_key, 'BIOS_README_FILEPATH': BIOS_DIST_FILEPATH, } context.update(system_datas) # Rendering template using context content = romsystem_template.render(**context) # Create target path if does not allready exists if not os.path.exists(system_path): click.echo(' > Path does not exist, create it : {}'.format( system_path)) if not run_dry: os.makedirs(system_path) # Create file with rendered template if not run_dry: with open(readme_path, 'w') as outfile: outfile.write(content.encode('UTF-8')) #print readme_path # Build bios readme file if bios: click.echo('* Start building bios readme files to: {}'.format(bios)) bios_systems_list = [] readme_path = os.path.join(bios, BIOS_README_FILENAME) bios_template = template_env.get_template(BIOS_README_TEMPLATE) for system_key, system_datas in Manifest.items(): bios_list = system_datas.get('bios', []) if len(bios_list) > 0: click.echo(' - System : {}'.format(system_key)) bios_systems_list.append( (system_datas.get('name', system_key), bios_list)) # Fill template context with system datas context = { 'systems': bios_systems_list, } context.update(system_datas) # Rendering template using context content = bios_template.render(**context) # Create file with rendered template if not run_dry: with open(readme_path, 'w') as outfile: outfile.write(content.encode('UTF-8')) #if __name__ == '__main__': #main()
from flask import Flask, request app = Flask(__name__) from mako.template import Template as MakoTemplates from mako.lookup import TemplateLookup from jinja2 import Environment as Jinja2Environment import tornado.template import random import string mylookup = TemplateLookup(directories=['/tpl']) Jinja2Env = Jinja2Environment(line_statement_prefix='#') def shutdown_server(): func = request.environ.get('werkzeug.server.shutdown') if func is None: raise RuntimeError('Not running with the Werkzeug Server') func() def randomword(length=8): return ''.join(random.choice(string.lowercase) for i in range(length)) @app.route("/reflect/<engine>") def reflect(engine): template = request.values.get('tpl') if not template: template = '%s'
def build(self, template_paths): self.env = Jinja2Environment(loader=FileSystemLoader(template_paths))
from webassets.ext.jinja2 import AssetsExtension import requests import urllib.parse import os from pprint import pprint from jsx_assets import ReactFilter from reverse_proxied import ReverseProxied app = Flask(__name__) app.wsgi_app = ReverseProxied(app.wsgi_app) assets = Environment() assets.init_app(app) register_filter(ReactFilter) assets_env = AssetsEnvironment('./static/js', '/media') jinja2_env = Jinja2Environment(extensions=[AssetsExtension]) jinja2_env.assets_environment = assets_env client_id = os.environ['CLIENT_ID'] client_secret = os.environ['CLIENT_SECRET'] config = { 'client_id': client_id, 'client_secret': client_secret, 'api_base_uri': 'https://api.sipgate.com', 'check_ssl': False, 'access_token': None, 'listen_host': '0.0.0.0' }
def test_add_page_advanced(temp_builds_dir, caplog): """ Add pages to registry with introspection and all """ basepath = temp_builds_dir.join("page_registry_add_page_advanced") # Create directory structure templates_dir = os.path.join(basepath.strpath, "templates") hiphop_dir = os.path.join(basepath.strpath, "templates", "hip") os.makedirs(templates_dir) os.makedirs(hiphop_dir) # Create dummy templates skeleton_template = os.path.join(templates_dir, "skeleton.html") index_template = os.path.join(templates_dir, "index.html") dummy_template = os.path.join(templates_dir, "dummy.html") base_template = os.path.join(templates_dir, "hip/base.html") hiphop_template = os.path.join(templates_dir, "hip/hop.html") inclusion_template = os.path.join(templates_dir, "_inclusion.html") with open(skeleton_template, "w") as fp: fp.write( ( """<html><body>""" """{% block content %}Nope{% endblock %}""" """</body></html>""" ) ) with open(index_template, "w") as fp: fp.write( ( """{% extends "skeleton.html" %}""" """{% block content %}Index{% endblock %}""" ) ) with open(dummy_template, "w") as fp: fp.write( ( """{% extends "skeleton.html" %}""" """{% block content %}Hello World!{% endblock %}""" ) ) with open(base_template, "w") as fp: fp.write( ( """{% extends "skeleton.html" %}""" """{% block content %}Base{% endblock %}""" ) ) with open(hiphop_template, "w") as fp: fp.write( ( """{% extends "hip/base.html" %}""" """{% block content %}Base {% include '_inclusion.html' %}""" """{% endblock %}""" ) ) with open(inclusion_template, "w") as fp: fp.write(("""I'm an inclusion""")) # Dummy settings and registry settings = DummySettings() reg = PageRegistry() # Init Jinja environment jinja_env = Jinja2Environment( loader=FileSystemLoader(templates_dir), ) # Make some views using templates index_view = PageViewBase( title="Index", destination="index.html", template_name="index.html", settings=settings, ) foo_view = PageViewBase( title="Foo", destination="foo.html", template_name="dummy.html", settings=settings, ) bar_view = PageViewBase( title="Bar", destination="bar.html", template_name="dummy.html", settings=settings, ) french_view = PageViewBase( title="French", destination="localized/{language_code}.html", template_name="hip/hop.html", settings=settings, ) english_view = PageViewBase( title="English", destination="localized/{language_code}.html", template_name="hip/hop.html", lang="fr", settings=settings, ) # Add page views without introspection reg.add_page(index_view, index_view.introspect(jinja_env)) reg.add_page(foo_view, foo_view.introspect(jinja_env)) reg.add_page(bar_view, bar_view.introspect(jinja_env)) reg.add_page(french_view, french_view.introspect(jinja_env)) reg.add_page(english_view, english_view.introspect(jinja_env)) print(reg.elements) assert reg.elements == { "index.html": set( [ "index.html", ] ), "dummy.html": set( [ "bar.html", "foo.html", ] ), "hip/base.html": set( [ "localized/fr.html", "localized/en.html", ] ), "_inclusion.html": set( [ "localized/fr.html", "localized/en.html", ] ), "hip/hop.html": set( [ "localized/fr.html", "localized/en.html", ] ), "skeleton.html": set( [ "index.html", "bar.html", "foo.html", "localized/fr.html", "localized/en.html", ] ), } assert reg.get_pages_from_dependency("index.html") == [ index_view, ] # Checking skeleton usage from pages results = sorted( reg.get_pages_from_dependency("skeleton.html"), key=lambda obj: obj.destination ) attempted = sorted( [ index_view, foo_view, bar_view, english_view, french_view, ], key=lambda obj: obj.destination, ) assert set(results) == set(attempted) # Checking hip base usage from pages results = sorted( reg.get_pages_from_dependency("hip/base.html"), key=lambda obj: obj.destination ) attempted = sorted( [ english_view, french_view, ], key=lambda obj: obj.destination, ) # Checking inclusion usage from pages results = sorted( reg.get_pages_from_dependency("_inclusion.html"), key=lambda obj: obj.destination, ) attempted = sorted( [ english_view, french_view, ], key=lambda obj: obj.destination, ) assert set(results) == set(attempted)
def process_dir(self, root, directory=''): currentpath = os.path.join(root, directory) for listing in os.listdir(currentpath): relpath = os.path.join(directory, listing) src_fullpath = os.path.join(currentpath, listing) replaced_relpath = self.replace_path(relpath) proceed = project_template_filter(self.blueberrypy_config, relpath) # hack to preprocess jinja2 html templates if isinstance(proceed, Jinja2Environment): jinja2_env = proceed else: jinja2_env = Jinja2Environment() if proceed: if os.path.isdir(src_fullpath): dest_fullpath = os.path.join(self.dest, replaced_relpath) if not self.dry_run: if not os.path.exists(dest_fullpath): os.makedirs(dest_fullpath) else: print("created directory " + dest_fullpath) self.process_dir(root, relpath) else: dest_fullpath = os.path.join(self.dest, replaced_relpath) head, tail = os.path.split(dest_fullpath) if tail.endswith("_tmpl"): dest_fullpath = os.path.join(head, tail[:-5]) with open(src_fullpath) as infile: tmpl = jinja2_env.from_string(infile.read()) if not self.dry_run: if self.overwrite or not os.path.exists( dest_fullpath): with open(dest_fullpath, 'w') as outfile: outfile.write( tmpl.render(self.blueberrypy_config)) elif os.path.exists(dest_fullpath): while True: print( "%s already exists, " "do you wish to overwrite it?" % dest_fullpath, "[Y]es [N]o [A]ll [C]ompare the files >> ", sep='\n', end='') i = getchar().upper() if not isinstance(i, type("")): i = i.decode('ascii') if i not in "YNAC": continue print(i.upper()) if i == 'Y' or i == 'A': with open(dest_fullpath, 'w') as outfile: outfile.write( tmpl.render( self.blueberrypy_config)) if i == 'A': self.overwrite = True break elif i == 'N': print("%s has been skipped." % dest_fullpath) break elif i == 'C': with open(dest_fullpath) as infile: old = infile.read() new = tmpl.render( self.blueberrypy_config) print("\n".join( difflib.unified_diff( old.splitlines(), new.splitlines(), dest_fullpath + ".old", dest_fullpath + ".new"))) continue else: print("created file " + dest_fullpath) print(tmpl.render(self.blueberrypy_config)) else: if not self.dry_run: if self.overwrite or not os.path.exists( dest_fullpath): shutil.copy(src_fullpath, dest_fullpath) elif os.path.exists(dest_fullpath): while True: print( "\n%s already exists, " "do you wish to overwrite it?" % dest_fullpath, "[Y]es [N]o [A]ll [C]ompare the files >> ", sep='\n', end='') i = getchar().upper() if not isinstance(i, type("")): i = i.decode('ascii') if i not in "YNAC": continue print(i.upper()) if i == 'Y' or i == 'A': shutil.copy(src_fullpath, dest_fullpath) if i == 'A': self.overwrite = True break elif i == 'N': print("%s has been skipped." % dest_fullpath) break elif i == 'C': with open(dest_fullpath) as infile: old = infile.read() with open(src_fullpath) as infile: new = infile.read() print("\n".join( difflib.unified_diff( old.splitlines(), new.splitlines(), dest_fullpath + ".old", dest_fullpath + ".new"))) continue else: print("copied file " + dest_fullpath)